Invalid Characters in Path while Compression in C# - c#

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).

Related

C# - Illegal characters in path

I have a database table that containing file paths of excel files that I import using a C# script.
The script works fine unless the filepath contains spaces e.g. C:\Temp\My Excel File.xls and I get an Illegal characters in path error message. Unfortunately I am not able to change the file names at the source.
If I hard code the file path to be as below it works fine.
String Filepath = #"C:\Temp\My Excel File.xls";
How do I alter this so I can include a string variable that will store the filepath from the database e.g.
String Filepath = //Code to get FilePath from database
StringCorrectedFilePath = #+FilePath;
Thanks in advance of any help
Edit: Issue is caused by files that start with a number creating invalid escape sequence. e.g. C:\Temp\20160611 My Excel File.xls
Edit 2: SOLVED - Error was caused by carriage return characters appearing after the file extension. Please see my answer for the solution.
Whether you do this
String Filepath = #"C:\Temp\My Excel File.xls";
or this
String Filepath = "C:\\Temp\\My Excel File.xls";
the string stored in memory is just C:\Temp\My Excel File.xls, whatever the debugger may tell you. So when you read some string from somewhere (database, file, user input, ...) you don't need to "escape" backslashes. So just use that string.
Path.GetInvalidFileNameChars
FilePath = string.Concat(FilePath.Split(System.IO.Path.GetInvalidFileNameChars())).Trim();
Well you can replace blank space with %20 character and while retrieving replace back with blank space again like (you may as well choose to use regular expression for the same)
String Filepath = #"C:\Temp\My Excel File.xls";
Filepath = Filepath.Replace(" ", "%20");
While retrieving back
string mypath = pathyouhavegotfromDB.Replace("%20", " ");
I think you need to put quotation marks around the path with spaces.
string filepath = #"C:\Temp\My Excel File.xls";
filepath = $"\"{filepath}\"";
Thanks for everyone's help, I tried all of these and unfortunately they didn't work which led me to believe that the issue wasn't what I originally thought.
It turns out that the files causing the Illegal characters in path all had carriage return characters at the end of the file name, after the file extension.
To resolve this I used the following code and now it works perfectly
FilePath = FilePath.TrimEnd('\r', '\n');
Thanks everyone for your help.
Try this:
String StringCorrectedFilePath = #""+ Filepath;

How specify generated folder(Directory) Name in C#

I have a C# application (WCF soap service) that is creating PDF documents and save in in the path that is defined in web.config. Consider for example path is: C:\Doc\Pdf\ that in the code path is in location variable. I like to generate folders for each day and stores the pdfs for that day on its folder.
I tried to use CreateDirectory but I don't know how specify name of the folder to generate.
This code only save the PDF in the C:\Doc\Pdf\ and it is not creating any directory:
string pdfFileName = "Application" + "_" + documentData.APPLICATIONDATE.ToString("MMddyyyy") + "_" + documentData.APPLICATIONDATE.ToString("hhmmsstt") + "_" + documentData.BorrowerLastName;
location = ConfigurationManager.AppSettings["PdfPath"].ToString();
DirectoryInfo di =System.IO.Directory.CreateDirectory(location);
wordDoc.SaveAs(location + pdfFileName, WdSaveFormat.wdFormatPDF);
In this context I think that you could simply use the Directory.CreateDirectory method passing the combined path that you expect to be created.
The Directory method called CreateDirectory works creating all the directories missing in the path specified and if the path already exists doesn't throw exceptions, it simply does nothing
So your code coulde be
string dayPath = DateTime.Today.ToString("yyyyMMdd");
string newPath = Path.Combine(location, dayPath);
Directory.CreateDirectory(newPath);
........

How to handle whitespaces in paths in command line parameters

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);

Unsupported format while using the correct format

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().

C# create file with same name as folder name, with extension

Suppose I have a folder called test.
Now I pass that folder into a program and it will output a file called test.xyz in the same directory that contains the target folder.
The general logic I'm using is something like
string outDir = Path.GetDirectoryName(path);
string outName = Path.GetFileName(path).TrimEnd("\\".ToCharArray()) + ".xyz";
string outFile = Path.Combine(outDir, outName);
Which works, but it seems kind of excessive to perform so many operations just to build my new filename.
1: Can I reduce the number of Path calls to achieve my result?
2: Can I do something about the second line to avoid trimming and also avoid using that add operation?
This seems to work in my quick tests:
string outFile = Path.GetFullPath(path) + ".xyz";
Although I just realized your path may include a trailing slash already. If you can't change it to avoid that, you'll still have to include the .TrimEnd() call.
In my test, I'm using var path = #"C:\Windows\System32";.
You could use a FileInfo for that!
string path = #"C:\Windows\System32\";
FileInfo fi = new FileInfo(path);
string outFile = fi.DirectoryName + ".xyz";
works like a charm. even with trailing slash in the directory string

Categories