0

I have the problem with whitespaces in my console application. My application is crashing because of not allowed chararcters.

My application is expecting an argument which is a path of the filesystem. So it will be called like this

myProg.exe "D:\tmp\with whitespace\" 

With that information I want to create a file in the given folder, but this is not possible because of not allowed char.

String pdfName = "foobar.pdf String datapath = args[0]; String targetJobFile = datapath + pdfName + ".txt"; 

I can see in the debugger that the targetJobFile value is

 "D:\tmp\with whitespace\"foobar.pdf.txt 

And there i receive the exception. Thanks

2
  • 1
    You should use Path.Combine, it will handle issues like this. - Path.Combine on MSDN Commented Oct 20, 2014 at 17:57
  • does this line String pdfName = "foobar.pdf even compile? your parameter should work fine, as they are enclosed in double quotes Commented Oct 20, 2014 at 17:57

3 Answers 3

1

You need to remove the quotes from the argument, so before using it, use Trim:

String realArg = args[0].Trim('"'); 

You already have the \ that Path.Combine would give you; but if you don't want your users to have to enter it, using Path.Combine is a good way to get the path separator character into your string.

Sign up to request clarification or add additional context in comments.

Comments

0

Why not just check for existence of " character and replace them before making the full path like

 datapath = datapath.Replace("\"",""); String targetJobFile = datapath + pdfName; 

Comments

0

You can go one step ahead and use Path.GetInvalidPathChars() which will return all invalid characters not allowed in path names and remove it from your path as follows -

modifiedPathName = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidPathChars())))).Replace(PathName, replaceChar);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.