Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating File Path w/Spaces in C#

I'm something of a n00b at C# and I'm having trouble finding an answer to this, so if it's already been answered somewhere feel free to laugh at me (provided you also share the solution). :)

I'm reading an XML file into a GUI form, where certain elements are paths to files that are entered into TextBox objects. I'm looping through the controls on the form, and for each file path in each TextBox (lol there's like 20 of them on this form), I want to use File.Exists() to ensure it's a valid file.

The problem with this is that the file path can potentially contain spaces, and can potentially be valid; however File.Exists() is telling me it's invalid, based entirely on the spaces. Obviously I can't hard-code them and do something like

if (File.Exists(@"c:\Path To Stuff"))

and I tried surrounding the path with ", like

if (File.Exists("\"" + contentsOfTextBox + "\""))

but that didn't make a difference. Is there some way to do this? Can I escape the spaces somehow?

Thank you for your time. :)

like image 840
dmn Avatar asked Feb 11 '26 16:02

dmn


1 Answers

File.Exists works just fine with spaces. There is something else giving you a problem I'll wager.

Make sure your XML reader isn't failing to read the filename (parts of XML do not allow spaces and some readers will throw an exception if they encounter one).

like image 87
Ron Warholic Avatar answered Feb 14 '26 06:02

Ron Warholic