I'm experiencing a strange issue here and not quite sure what I'm missing. I ran the code below and it did create a .zip file and I watched the size increase from 0KB to 8,992KB. However, as I open the .zip file, I don't see any file. And if I try to "Extract All..." from explorer, it shows "Windows can not complete the extraction" because the .zip file "is invalid". Any idea what I did wrong?
if (File.Exists(ZipName))
File.Delete(ZipName);
using (ZipArchive archive = ZipFile.Open(ZipName, ZipArchiveMode.Create))
{
foreach (string sFileName in FileNames)
{
archive.CreateEntryFromFile(sFileName,sFileName,CompressionLevel.Optimal);
}
}
You need to strip the drive letter from the entryName, which is the 3rd parameter to CreateEntryFromFile().
So instead of
archive.CreateEntryFromFile(sFileName, sFileName, CompressionLevel.Optimal);
Use
archive.CreateEntryFromFile(sFileName, sFileName.Substring(3), CompressionLevel.Optimal);
I ran into the same problem, and I discovered a solution. It turns out that I was feeding the method a full path to the file for both filename arguments, like so:
// This gets a list of files with their full paths
var fileList = Directory.GetFiles(_outputDir, "*.txt");
foreach (var file in fileList)
{
archive.CreateEntryFromFile(file, file, CompressionLevel.Optimal);
}
That gave me the same problem you had -- an empty zip file, which was invalid. (By the say, my file paths weren't that long -- they were C:\Results\[some_guid].txt.)
The solution was to get the files as FileInfo objects, then for the first argument use the full path and for the second argument just use the file name, like so:
// This gets a set of FileInfo objects, with a FullName property that is
// the full path to the file, and a Name property that is just the file name.
var directoryInfo = new DirectoryInfo(_outputDir);
var fileList = directoryInfo.GetFiles("*.txt");
foreach (var file in fileList)
{
archive.CreateEntryFromFile(file.FullName, file.Name, CompressionLevel.Optimal);
}
This ended up working perfectly. If I opened the zip file, the files were there. If I extracted it, the extraction worked and the files seemed to be valid.
Related
Hello StackOverflow community,
I'm working for a C# web application that can show all necessary files in one folder. For example, you have a folder named "Maps" that stores all information about New York City. I will describe this folder here: The bolded word is folders.
Folder Maps:
->NewYorkCity
->>satellite.png
->>coordinates.txt
->>bridges.png
->>Road1
->>>satellite1.png
->>>roads.txt
->>>houses.png
As you can see, inside folder Maps we have folder NewYorkCity, and inside of this, we have folder Road1. Now I want to collect all files that have "*.png" type. It means I want to collect all images inside the root folder. The problem here is the algorithm to collect the file. I have thought to use "for loops" but I don't know the number of subfolders so I assumed it was impossible.
Here is the code to list the file with specified type that I have used but it works for files that in one folder and doesn't have any subfolders.
DirectoryInfo dInfo = new DirectoryInfo(zipPath); //Assuming Test is your Folder
FileInfo[] Files = dInfo.GetFiles("*.png"); //Getting Text files
string str = "";
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
}
I hope you understand my question. Thank you.
You could start by reading the documentation, where you would find System.IO.DirectoryInfo.
Create a DirectoryInfo instance, and use, depending on what you want/need, any of its methods
EnumerateDirectories()
EnumerateFiles()
EnumerateFileSystemInfos()
Like so:
DirectoryInfo di = new DirectoryInfo(#"c:\Maps");
foreach (var fsi in di.EnumerateFileSystemInfos("*", SearchOptions.AllDirectories)
{
// Do something useful with fsi here
}
How can I iterate and print all of the file paths of all .pdf files in a specific directory when using Directory.EnumerateFiles?
The following code only returns the path of the first .pdf file in the specified directory.
IEnumerable<string> files = Directory.EnumerateFiles(#"C:\MyFolder", "*.pdf*", SearchOption.AllDirectories);
foreach (string file in files) {
Console.WriteLine("File Path:{0}", file);
}
// Returns:
// C:\MyFolder\firstPdfFile.pdf
Again, what I want is to be able to print all of the paths of all pdfs files in a specified directory. What am I missing?
EDIT: I'm not getting any errors, but the only thing I see in the console is the path of the first pdf found in the specified directory and I was expecting to see the path of all pdf files in that directory.
haven't used function you written, but suggest you to try out below
string[] filePaths = Directory.GetFiles(#"c:\MyFolder\", "*.pdf",
SearchOption.AllDirectories);
// returns:
// "c:\MyFolder\fist.pdf"
// "c:\MyFolder\subdirectory\sss.pdf"
Am trying to loop through a folder and read all the XML files within it.
Am using the Directory.EnumerateFiles to read from the path.
My .cs file and the XML files folder lies in same path
"C:\User\Documents\Projects\TestTool"
Am using the below code to get read the files.
string path = #"..\TestCases\";
foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{
}
Using this am getting exception stating
Could not find path "C:\Program Files(x86)\Common Files\Microsoft
Shared\DevServer\TestCases"
This is pointing to the WebDev.WebServer20 path instead of the actual path.
Not sure why it is pointing to a completely different folder
I tried string path = #"\TestCases\"; But when I try like this it is throwing an exceptiopn stating
Could not find path "C:\TestCases"
What is the mistake am making? Please help
Try it:
string path = "..\\TestCases\\";
foreach (FileInfo file in new DirectoryInfo(path).EnumerateFiles("*.xml"))
{
string filePath = file.FullName;
}
Since it is running under WebDev server it will using WebDev.WebServer20.exe's path for all relative paths.
You must use: Server.MapPath("~") to get to your own root.
string path = Server.MapPath("~") + #"\TestCases\";
foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{
}
Please note if Server.MapPath("~") points to bin, then use it like Directory.GetParent(Server.MapPath("~")) + #"\TestCases\";
Assuming this is your target directory C:\User\Documents\Projects\TestTool\TestCases
I have what could be an unusual problem. My problem is that I have a collection of file paths which contain the filenames too. As the code loops round the collection it takes the string and creates a FileInfo object. With this object it then uses the MoveTo method to move the file to another location.
This all works well until it reaches a file with a zero length and says it cannot find the file. If I take this file and create a FileInfo object in a different application it works regardless of size. Does anyone know about what is causing this and how to solve it? Relevant code snippet below
IList<string> files = new List<string >();
files.add(file1);
files.add(file2);
foreach (string filepath in files)
{
FileInfo file = new FileInfo (filepath);
string newlocation = Path.Combine(dest, file.name);
file.MoveTo (newlocation); //exception thrown here on zero length
}
Try to call file.Refresh() before file.MoveTo(...).
Read Remarks in this page https://msdn.microsoft.com/en-us/library/system.io.fileinfo.exists.aspx
you need to use
System.IO.File.Move(Sourcefile, DestinationFile);
More details:https://msdn.microsoft.com/en-us/library/system.io.file.move(v=vs.110).aspx
One of my executable process produces two files. I want to move one file that is produced to shared drive. I am writing an automatic process to move the file from one location to shared drive. The only issue is file name changes every time the executable is run so I don't have the exact filename with me. I only have the extension, .xls. I have only one .xls file in my directory.
I tried doing this
File.Copy(#"*.xls", #"\\serv44\Application\testing\name\test2\*.xls", true);
It threw an error saying Invalid name. After moving the file to shared drive. I want to delete the .xls file.
File.Delete("*.xls");
any help will be appreciated
You should get file name and then do whatever you want with that file. I.e. if you have only one xls file in the source directory:
var targetDirectory = #"\\serv44\Application\testing\name\test2\";
var sourceFile = Directory.EnumerateFiles(sourceDirectory, "*.xls").FirstOrDefault();
if (sourceFile != null)
{
var sourceFileName = Path.GetFileName(sourceFile);
var targetFileName = Path.Combine(targetDirectory, sourceFileName);
File.Copy(sourceFileName, targetFileName);
File.Delete(sourceFileName);
}
Note: instead of copy and delete you can use single Move operation.
If you want to move several files from your source directory, then instead of taking first one process all found files in a loop:
foreach(var sourceFile in Directory.EnumerateFiles(sourceDirectory, "*.xls"))
{
var sourceFileName = Path.GetFileName(sourceFile);
var targetFileName = Path.Combine(targetDirectory, sourceFileName);
File.Move(sourceFileName, targetFileName);
}
This should give you that file name:
var fileName = Directory.GetFiles(yourDirectory, "*.xls").ToList().FirstOrDefault();