3

Possible Duplicate:
Figuring out whether string is valid file path?
In C# check that filename is *possibly* valid (not that it exists)

I have a method that expects a string which represents a file name with its full path.

I want to validate (Guard) this string in terms of its format to see whether it CAN really represent a file name (not the correctness of the path whether it exists or not)?

For example it should not be accepted if it is something like : "123C:\foo\"

What is the easiest way to do this check in C# ?

public void LoadFile(string fileName)
{
  var valid = Check if 'fileName' is in valid format.
  if(!valid)
      throw new ArgumentException(....
}
Community
  • 1
  • 1
pencilCake
  • 51,323
  • 85
  • 226
  • 363

1 Answers1

2

From the documentation:

In members that accept a path as an input string, that path must be well-formed or an exception is raised.

So you can do something like this:

public void LoadFile(string fileName)
{
    try
    {
        var path = Path.GetFullPath(fileName);
    }
    catch (NotSupportedException e)
    {
        throw new ArgumentException(...);
    }
}
NominSim
  • 8,447
  • 3
  • 28
  • 38