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
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.
Why not just check for existence of " character and replace them before making the full path like
datapath = datapath.Replace("\"","");
String targetJobFile = datapath + pdfName;
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);
Related
I have path with backslashes and space that I need to send as parameter to regedit.exe:
\\folder1\folder2\folder three\file.reg
Based on my knowledge using # in front of string should allow back slashes to be specified directly (without escaping). Here is my full code that I am trying to execute it on:
string path = #"\\folder1\folder2\folder three\file.reg"
Process regeditProcess = Process.Start("regedit.exe", file);
When I tried running the program, it gives me an error from regedit's output saying:
Cannot import \folder1\folder2\folder: Error opening the file. There may be a disk or file system error
Since error report backslashes correctly I am guessing the compiler or regedit does not read anything past the whitespace after "folder"
When passing arguments in the command line, you need to surround them with ". Try this:
string path = #"""\\folder1\folder2\folder three\file.reg""";
Process regeditProcess = Process.Start("regedit.exe", path);
Adding "" in a verbatim string will add a single double quote to the string so the resulting string will be "\\folder1\folder2\folder three\file.reg" which will then allow it to get passed correctly to regedit.exe.
I am having a problem where I am trying to ZIP up a file using the below code :-
Process msinfo = new Process();
msinfo.StartInfo.FileName = "msinfo32.exe";
string path = "\"" + Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + #"\test.nfo" + "\"";
string zippath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + #"\test.nfo";
MessageBox.Show(path);
msinfo.StartInfo.Arguments = #"/nfo "+path;
//msinfo.Start();
//msinfo.WaitForExit();
//MessageBox.Show("The File Has Been Saved!");
ZipFile.CreateFromDirectory(zippath, #"C:\Test.zip");
MessageBox.Show("Everything Is Done!");
The error that is coming is that the Folder path is not valid. I also tried by including quotation marks in the Zippath variable but it did not work.
PS - My machine name has 3 words so it has got spaces as well. Help is appreciated ^_^
The first argument of ZipFile.CreateFromDirectory should be a path of a directory, not a file (test.nfo in this case).
If you want compress the whole directory (e.g. the Desktop dir) then omit the "test.nfo" from the path, like this:
string zippath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
If you want to create a zip archive from only one file then use the ZipFileExtensions.CreateEntryFromFile.
One more thing: when you want to build a path from two or more components use the Path.Combine method instead of simple string concatenation. It can spare you from a lot of pain (like adding path separator characters).
Hey guys I have this piece of code that will first store a path in a variable, check if that path exists, if not create it. then take that path and add my file name to it.
Here is the code
appData = string.Format("{0}{1}\"", controller.Server.MapPath("~/App_Data/"), Guid.NewGuid().ToString());
if (!Directory.Exists(appData))
Directory.CreateDirectory(appData);
filePath = string.Format("{0}\"{1}", appData, model.File.FileName);
model.File.SaveAs(filePath);
data.Add("attachment", filePath);
But when it gets to the SaveAs function it states
Illegal character in path
AppDath = C:\Users\Ben\Documents\Team Foundation Server\Team
Projects\Shared\Orchard
1.6\Orchard\src\Orchard.Web\App_Data\392216b5-32ad-41f4-82bf-e074b13f25df\"
Any idea why?
use Path.Combine
filePath = Path.Combine(appData, model.File.FileName);
same to create appData path
appData = Path.Combine(controller.Server.MapPath("~/App_Data"), Guid.NewGuid().ToString());
Use
filePath = string.Format(#"{0}\"{1}", appData, model.File.FileName);
The # char show the compiler that the string doesn't have any backslashed characters.
Normaly, you use the \ prefix in some special chars, like \n means a newline. You string has a \, so the compiler tries to resolve it with the next char in the string.
Another way is to escape the backslash with the second one, like this:
filePath = string.Format(#"{0}\\"{1}", appData, model.File.FileName);
Im getting a "NotSupportedExeption was unhandled by user code - the specified path format is not supported" error, even thou I use a string as is requered.
string path = folder + "/" + filename;
fileByte = File.ReadAllBytes(path); // error here
any idea to what the problem is?
edited the code to this
string path = Path.Combine(folder, filename);
fileByte = File.ReadAllBytes(path);
the path is "F:\Web\Opgaver\Skirmer\Hjemmesiden\BETA\Skirmer 17-04-2012\Skirmer 17-04-2012\Billeder\Galleri\F:\Web\Opgaver\Skirmer\Hjemmesiden\BETA\Skirmer 17-04-2012\Skirmer 17-04-2012\Billeder\Galleri\2011\Vingsted\DSC_0001.JPG"
Error still happens. What I see is that ReadAllBytes requeres a string that shows the path, that I got, but it still shows error
You should not use / in the path, as the slash is an invalid character in Windows. Use Path.Combine to create it instead:
string path = Path.Combine(folder, filename);
I think that you want to use a backslash, or rather the property Path.DirectorySeparatorChar that returns the correct separator regardless of the file system:
string path = folder + Path.DirectorySeparatorChar.ToString() + filename;
Or you can use the Path.Combine method:
string path = Path.Combine(folder, filename);
What is the exact value of path variable?
Additionally, you should use Path.Combine to concatenate path parts into a full path.
As the documentation for File.ReadAllBytes states:
NotSupportedException - path is in an invalid format.
Your path is not in the correct format:
NotSupportedException path is in an invalid format.
MSDN: system.io.file.readallbytes
If the path you posted in your edited question really is the path you are trying read from then the reason you are getting the exception is because you have two colons in the path. The drive letter is repeated twice (F:\...F:\...).
The reason you end up with that path depends exactly on the contents of folder and filename in your call to Path.Combine(). It is unlikely that both folder and filename both start with the full path since Path.Combine() will return filename as the combined path in that case. It is most likely that your folder variable already contains two copies of the base path, with two drive letters and hence two colons and therefore causing the NotSupportedExeption, before you call Path.Combine().
string slink = "\\README.TXT";
string ipath = "C:\\Users\\Crystal\\Documents\\Visual Studio 2010\\Projects\\workspace\\workspace\\bin\\Debug";
string test = lpath+"\\workspace\\"+slink;
string test1 = "C:\\Users\\Crystal\\Documents\\Visual Studio 2010\\Projects\\workspace\\workspace\\bin\\Debug\\workspace\\README.TXT";
string ftpfullpath = myUri.ToString();
WebClient request = new WebClient();
FileStream file = File.Create(#test);
if i write FileStream file = File.Create(#test); i get error illegal characters.
if i write FileStream file = File.Create(#test1); it works!
i think something is wrong with gluing multiple string path values. i've tried also Path.Combine but also doesn't work
In your third line of code, you've used lpath instead of ipath - i am assuming that's a typo
Use this:
string resultPath= Path.Combine(p1, p2);
MSDN Reference
Taking it that lpath is a typo for ipath, the latter adds an extra slash (or set of slashes, depending on the context) before README.TXT.
That is to say,
\\workspace\\README.TXT
becomes,
\\workspace\\\\README.TXT
You're writing "..\\" + "\\...".
A path cannot have two consecutive \s.
The problem is your either your slink or your test. The code you have ends up with the following path:
C:\Users\Crystal\Documents\Visual Studio 2010\Projects\workspace\workspace\bin\Debug\workspace\\README.TXT
Notice the double slash before README.TXT?
This is caused because slink becomes:
\README.TXT
Then you are trying to combine that with:
C:\Users\Crystal\Documents\Visual Studio 2010\Projects\workspace\workspace\bin\Debug\workspace\
You can do 1 of 2 things to fix the problem:
Remove the \\ from the slink
Remove the trailing \\ from the "\\workspace\\" when you try to combine them
I would suggest option 1 - it clearly separates the filename from the path of the file. Having the \\ preceding the file implies that the filename also has its path info