I'm trying to write a method that extracts a zip file to a directory, finds a file in the extracted contents, reads the text in that file to a string, and returns that string. Here is my attempt
private string _getDataFile(string zipFile)
{
string pathToFolder = #"C:\Path\To\The\File";
foreach (char c in Path.GetInvalidPathChars())
{
pathToFolder = Regex.Replace(pathToFolder, c.ToString(), "");
}
string pathToFile = pathToFolder + #"\model.dat";
ZipFile.ExtractToDirectory(zipFile, pathToFolder);
string dataToReturn = File.ReadAllText(pathToFile);
return dataToReturn;
}
However, despite my foreach loop replacing illegal path characters, the program still throws an illegal characters in path exception at the ZipFile.ExtractToDirectory line no matter what directory I try to use and I have no idea why. Any help would be greatly appreciated.
According to a similar post, it looks like you may have a problem with a file name inside the target zip file; it is not a problem with your specified zip file name or directory. Try extracting the contents of the file manually to see if there are unusual file names.
You can iterate through all the entries and sanitize the filenames before extracting them by using this snippet that I wrote here: ZipFile.ExtractToDirectory "Illegal characters in path"
Related
I am very new to coding and I am having some trouble in extracting a zip file to a directory.
Currently this is my code
string zipPath = "Typhoon.zip";
string extractPath = str_xp11_loc + #"\Resources\Plugins";
ZipFile.ExtractToDirectory(zipPath, extractPath);
When using code above I am getting Invalid characters in path
I have tried code that creates a txt file with the extracting location and adding the "#"\Resources\Plugins" via FileWriter and that sorta works but only extracts to the first few folders defined. When I use filewriter it creates a new line with "Resources\Plugins" When using this method it extracts to the first line for example C:\Folder1\Output.
I have tried using string result = Regex.Replace("Xp11_install.txt", #"\r\n?|\n", "");
to try and remove the the line break but that has not worked.
Is it possible to extract file using the method above?
Any insight is greatly appreciated
I'm not quite sure if this is what you are searching for, but in my case I created a ZIP file with a folder and Subfolder inside.
With the following modified code that you provided:
string zipPath = #"YourFilePath.zip";
string extractPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
ZipFile.ExtractToDirectory(zipPath, extractPath);
I was able to extract that file, in this example to the MyPictures folder, with all the Subfolders.
If this is not what you were searching for, maybe have a look at the docs documentation:
ZipFile.ExtractToDirectory Method
I have a very simple C# program which iterates over a number of files and replaces a string in all the files.
However, when I compare these files using Git, it highlights a change to all my files.
My C# code is:
string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
string fileText = File.ReadAllText(fileName, Encoding.UTF8);
string newText = fileText.Replace("hello", "goodbye");
File.WriteAllText(fileName, newText, Encoding.UTF8);
}
Which as far as I'm concerned, looks good.
However, when I run this program and execute git status on the repository, I see differences in every file.
Using a program like Github Desktop or SourceTree reveals the following changes:
Github Desktop
Sourcetree
Thank you for any tips or ideas anyone may have. They're greatly appreciated. :)
This character is the Unicode Byte Order Mark (BOM) preamble, which is automatically added by the WriteAllText method.
If you want to write files without BOM, you have to create custom encoding:
Encoding utf8NoBom = new UTF8Encoding(false);
And you then pass the instance as third parameter of the WriteAllLines method:
File.WriteAllText(fileName, fileText, utf8NoBom);
Thanks to the comment from #Amy I have managed to identify the issue.
I assumed all my files were encoded as UTF-8, but this wasn't the case.
Using the answer specified here I was able to identify the encoding of my file and using that when reading/writing from/to the file.
My code now looks like this (using the 'GetEncoding' method specified in this answer):
string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
Encoding fileEncoding = GetEncoding(fileName);
string fileText = File.ReadAllText(fileName, fileEncoding);
string newText = fileText.Replace("hello", "goodbye");
File.WriteAllText(fileName, newText, fileEncoding);
}
I have been tasked to build a WPF App which uses a user input form to gather information, and then save the information as string in a text file, whose name is created as a result of user input. The UI and user input are working, but the string will not save to the text file. Whenever the code is debugged it throws a "file path not supported exception".
This is the code for my writing to the file:
System.IO.File.WriteAllLines("C:\\Users\\jhump\\Desktop\\TestingApp\\"+filename+"\\", data);
Where data is a string array containing the string to be saved, and filename is the concatted name for the file to be saved as.
Thank you in advance for your help!
You need to escape \ characters by using an extra backslash like this \\. Also you can use String Literals, like #"C:\Users\..." instead if you don't want to use double backslashes.
string[] data = { "Some", "Thing", "Foo", "Bar" };
string filename = "foo.txt";
System.IO.File.WriteAllLines("C:\\Users\\jhump\\Desktop\\TestingApp\\" + filename, data);
You have to concat the names of the directory or either escape the \ backslash:
...WriteAllLines(#"C:\yourpath\here\filename.txt",data)
best way for the user home folder is to use special folder paths:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
I am a newbie to programming so i am hoping support for my problems from all my friends
This is the problem
I have used the loation as 2DB to read a csv file.It works well when I give the file name also But I want to give only location and program needs to select the file
string path = "G:\kaash\2DB\";
string[] row_text = System.IO.File.ReadAllLines(""+path+", *.csv");
string[] data_col = null;
This code will help you to find all .csv files as a list of strings from the specified directory.
string path = #"G:\kaash\2DB\";
List<string> csvIn2DB = System.IO.Directory.GetFiles(path, "*.csv", SearchOption.TopDirectoryOnly).ToList();
By modifying the search pattern you can locate your files more specifically. You can change the SearchOption to AllDirectories if you want to extend the search to inner folders of the specified directory.
Let you need to get all your .csv file names follows the pattern "FILECSV_xxxxxx.csv", then the search pattern will be like this: FILECSV_*.csv
Tried several times to make this work but with several failures.
let me explain what i've tried to do: 1.Unrar the files in zip format (working) 2.Unraring to a named directory (unrars) 3.Copying from unrars folder to another folder(not working) So my question is : Did i used a correct overwrite format? i set the bool overwrite to true.
foreach (string fisier in Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories))
{
System.IO.File.Copy(fisier, fisier.Replace(TheSourcePath, TheDestinationPath), true);
}
Seems like an odd way to get the destination path to me, can't you just have it as a string?
It might be that the string replace isn't creating a valid path.
I assume `TheDestinationPath' is a const, in which case is won't have the file name on it, or you'll be copying over a file from the second iteration.