public static bool ValidateFilepath(string path)
{
if (path.Trim() == string.Empty)
{
return false;
}
string pathname;
string filename;
try
{
pathname = Path.GetPathRoot(path);
filename = Path.GetFileName(path);
}
catch (ArgumentException)
{
// GetPathRoot() and GetFileName() above will throw exceptions
// if pathname/filename could not be parsed.
return false;
}
// Make sure the filename part was actually specified
if (filename.Trim() == string.Empty)
{
return false;
}
// Not sure if additional checking below is needed, but no harm done
if (pathname.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
{
return false;
}
if (filename.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
{
return false;
}
return true;
}
Just some random development ramblings mostly related to the Microsoft .NET platform.
Monday, August 18, 2008
Validate a file path using C#
I finally found a good algorithm to validate a file path (had to fix two bugs in it though). I use this static method in Windows Forms when the user is allowed to enter a path. I add a text changed event on the textbox and call this method to enable or disable an OK button.
Subscribe to:
Post Comments (Atom)
Can't RDP? How to enable / disable virtual machine firewall for Azure VM
Oh no! I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore. I did ...
-
Oh no! I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore. I did ...
-
Here is a full test program that demonstrates how to use SharpZipLib to zip an XElement into a byte array. This allows you to transfer larg...
3 comments:
I tried your function in my system (Windows Vista Enterprise, SP2) and it accepts the following path as valid:
C:\oslo?\path\Somewhere.pdf
I read the specification for Path.GetInvalidPathChars() in msdn and it seems like it doesn't guarantee to return the whole set of invalid path chars in a given environment.
One workaround I found to find out if a given path was actually valid was to apply your function first, and if it succeeded, then I tried creating the file (or directory). That way, if the path or the filename were invalid, the system would not allow me to create them.
I don't really like this last approach, but it works. If you can find out something better, please post it.
Thank you!
Substituting Path.GetFullPath for Path.GetPathRoot seems to work for me...
beforeandafterw,
Yes, you are correct that GetRootPath and GetFullPath won't throw an exception when the path is invalid. Unfortunately, these methods still returns a value.
Knowing whether a path is (or will be) valid is important in situations where you want to use a path to create a file after user input. In this case, it is nice to use the posted algorithm to verify the path is valid...either during or after user input. If you don't, then a subsequent exception may need to be handled when a file creation is performed.
Post a Comment