Folder enumeration to identify a specific file leads to nothing - c#

The below code does not identify the filepath and store it in the variable "compare_conv_filepath". This is a bug.
The code is written to enumerate files in a folder and identify a file if the filename is identical to "1.xlsx" and then store the entire filepath in a string variable.
The folder it enumarates will always ONLY have 1 file identical to "1.xlsx", but the folder might NOT have a file identical to "1.xlsx". Then the foreach should do nothing or a null value be given. The folder will always have ONE file called "orgFile_[some_filename]" and this filename could be "orgFile_1.xlsx".
Can you help?
using System.IO.Enumeration;
// Identify converted spreadsheet in folder
var conv_file = from file in
Directory.EnumerateFiles(folder)
where file.Equals("1.xlsx")
select file;
foreach (var file2 in conv_file)
{
compare_conv_filepath = file2.ToString();
// Inform user of comparison
Console.WriteLine(compare_conv_filepath);
Console.WriteLine($"--> Comparing to: {compare_org_filepath}");
}

You're comparing the file path with it's name. try isolating the name using Path.GetFileName():
where Path.GetFileName(file).Equals("1.xlsx")

Related

Package a Folder in C#

I'm looking to make a program to make my life easier, I need to be able to easily select a folder, which I can do, I don't need help with that. I want to take the directory of a folder, and put that folder into a new folder with a specified name, and then zip up that folder into a zip format in which I can change the name and filetype of. Is this possible in vanilla C#? I've only ever done files for text and I've never looked at moving and packaging files. SO I'm really clueless, I'd just like to be guided into the right direction.
Edit: I found this code online, but I need to put the folder inside another folder, may I adapt upon this to do so?
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
So, after an extended chat discussion, here's what we've established.
The goal is to put the contents of a source directory into a zip with the following structure:
- Payload
|- name of source
|-- contents of source
Okay, so, starting from an input path called startPath:
var parent = Path.GetDirectoryName(startPath);
var payload = Path.Combine(parent, "payload");
Directory.CreateDirectory(payload); // ensure payload ex
Directory.Move(startPath, Path.Combine(payload, Path.GetFileName(startPath));
var zipPath = Path.Combine(parent, "export.zip");
File.Delete(zipPath);
ZipFile.CreateFromDirectory(payload , zipPath, CompressionLevel.Optimal, true);
The key is that true in the CreateFromDirectory call, that puts the entries in the archive under a directory with the same name as the directory being zipped (in this case, "payload"). Feel free to change CompressionLevel to other values if you want.
Now, this has the side effect of actually physically moving the source directory, which might not be the best user experience. If you want to avoid that, you'll have to basically do what ZipFile.CreateFromDirectory does by hand, which is to enumerate the source directory yourself and then copy the files into the zip archive (in which case you can name those files whatever you want):
var parent = Path.GetDirectoryName(startPath);
var zipPath = Path.Combine(parent, "export.zip");
File.Delete(zipPath);
using var zip = ZipFile.Open(zipPath, ZipArchiveMode.Create);
foreach(var file in Directory.EnumerateFiles(startPath, "*", SearchOption.AllDirectories))
{
// get the path of the file relative to the parent directory
// this gives us a path that starts with the source directory name
// e.g. C:\example\start\file.txt -> start\file.txt
var relativePath = Path.GetRelativePath(parent, file);
// construct the path of the entry in the archive
// this is "Payload", and then the relative path of the file
// we need to fix up the separators because zip entries use /
// e.g. start\file.txt -> Payload/start/file.txt
var entryPath = Path.Combine("Payload", relativePath).Replace(Path.DirectorySeparatorChar, '/');
// put the file in the archive
// to specify a compression level, pass it as the third parameter here
zip.CreateEntryFromFile(file, entryPath);
}

Finding version of multiple files in a folder C#

I'm working on tool which is comparison between two folders.
Here's the test cases need to satisfy,
Have to check file names which are similar in both folders -- Done
The files having same name have to undergo version comparison -- Here is the problem
I can find the version of a file giving the path of single file and name.exe. But, I want to get all files version.
I don't want to give every path of single file and name.
Here is part of a code,
if (File.name == File1.Name)
{
versioncheck(file.name);
}
private void versioncheck(string Name)
{
var versionInfo = FileversionInfo.GetversionInfo(#"C:\mainfolder\chrome.exe");
String version = versionInfo.FileVersion;
Console.WriteLine("file version" + version);
}
This code giving single file check, but I want to get all files in a loop or something.
Is there any way?

How to check if a file exists or not in the directory the executable is?

How can I check if a file exists or not in the directory the executable is?
I know how I could code it like this.
string path = Application.StartupPath + "config.cfg"
if(!FileExists(path))
{
//create the file
}
But the problem I am facing is that, the file is created every single time, even when the file exists, overwriting the data of the cfg file with the default ones.
You are not creating the possible file path properly. Use Path.Combine like:
string path = Path.Combine(Application.StartupPath, "config.cfg");
You are getting a path without terminating \ from Application.StartupPath, later you are concatenating the file name to it, This will create an invalid path, and since that doesn't exist, you check fails.
Just to show, the actual reason for getting the error, you can fix your code like:
string path = Application.StartupPath +"\\"+ "config.cfg";
But, do not use the above code, instead use Path.Combine to join multiple path elements.

How to check if a text file has generated in a particular path or not in C#

one .txt file is getting exported inside the path - D:\work\int\retail\store\export after i run a Stored procedure. Now i want to validate in C# whether the .txt file has come or not in this path. I am using the below syntax according to which file.exists() is still returning false even though .txt file is there in the export location.what's going wrong here?Any help will be appreciated on this.how can i get the latest file name coming in this location dynamically and pass to this below query?
var FilePath = #"D:\work\int\retail\store\export";
if(File.Exists(FilePath))
{
//do this
}
for checking if specific files exists on a path use File.Exists(path), which will return a boolean indicating whether the file at path exists. In your case
if(File.Exists(#"D:\work\int\retail\store\export\one.txt"))
{
//do this
}
In your example you are missing the filename.
If you want to fetch the latest file from some directory use this code.
var directory = new DirectoryInfo(#"D:\work\int\retail\store\export");
var File = directory.GetFiles()
.OrderByDescending(f => f.LastWriteTime)
.First();
You have to create a variavble of DirectoryInfo Class which takes directory path as parameter, Here I have passed your directory path D:\work\int\retail\store\export, Now GetFiles() function returns all the files inside the directory and I have sorted them in Descending order by LastWriteTime property of files, and fetched the first file which will be the latest file in the directory. Hope it helps.
To get the .txt file only Please use below code. It will get you the latest txt file.
var directory = new DirectoryInfo(#"C:\Users\Saket\Downloads\");
var File = directory.GetFiles().Where(c=>c.Extension == ".txt")
.OrderByDescending(f => f.LastWriteTime)
.First();
You need to mention your text file name in the path, if your txt file is called x.txt for example, you need to write the path as var FilePath = #"D:\work\int\retail\store\export\x.txt";

Creating a zip file with ionic.zip

I have the following code set up to create a zip file of a set of doucments:
public bool CreateDocumentationZipFile(int documentIdentifier, string zipDestinationPath, IList<string> documentPaths)
{
bool zipped = false;
if (documentPaths.Count > 0)
{
using (ZipFile loanZip = new ZipFile())
{
loanZip.AddFiles(documentPaths, false, zipDestinationPath);
loanZip.Save(string.Format("{0}{1}.zip",zipDestinationPath, documentIdentifier.ToString()));
zipped = true;
}
}
return zipped;
}
The issue I have is that when the zip file is created, the folder structure is maintaned within the zip file:
e.g
I am creating a zip of a selection of documents located at
C:\SoftwareDevelopment\Branches\ScannedDocuments\
When the created zip file is opened, there is a folder structure within the zip as follows:
Folder 1 ("SoftwareDevelopment")
Inside Folder 1 is folder 2 ("Branches")
Inside Folder 2 is folder 3 ("ScannedDocuments")
the scanned documents folder then contains the actual scan files.
Can anyone tell me how I can just have the scan files in the zip without the folders path being maintained?
The documentation states that the third parameter
directoryPathInArchive (String)
Specifies a directory path to use to override any path in the file
name. This path may, or may not, correspond to a real directory in the
current filesystem. If the files within the zip are later extracted,
this is the path used for the extracted file. Passing null (Nothing in
VB) will use the path on each of the fileNames, if any. Passing the
empty string ("") will insert the item at the root path within the
archive.
So if you always want to have the files added to the root of your zip archive, change
loanZip.AddFiles(documentPaths, false, zipDestinationPath);
to
loanZip.AddFiles(documentPaths, false, "");

Categories