SmallestWish
SmallestWish

Reputation: 115

File path validation

I have to validate user input for file path. So far what I have tried is given below in the code. The code works fine for some cases e.g.

C:\ (valid) (my code returns valid)

C:\(valid) (my code returns valid)

C:+space+\ (my code returns valid but I want to take it as invalid)

C:+space+ filename (my code returns valid but I want to take it as invalid)

It should consider "spaces" between and after the "\" as invalid.

public bool FilePathValid(string path)
        {
            try
            {
                Path.GetFullPath(path);
                Path.GetFileName(path);
                return Path.IsPathRooted(path);
            }
            catch (Exception e)
            {                   
                return false;
            }
        }

NOTE: I only want to try regex when I have no other options because as once said you try to solve your problem with regex and ends up having two.

Upvotes: 0

Views: 1986

Answers (1)

CodeCaster
CodeCaster

Reputation: 151720

So you're not interested in actually validating a path nor checking whether a path points to an existing file or directory, you just want to check if a path separator is preceded or followed by a space?

Then do that:

if (path.Contains(@" \") || path.Contains(@"\ "))
{
    // do your magic
}

Upvotes: 1

Related Questions