I need to open file from folder by part of name.
I have files in one folder for example all files are in c:\temp\
Names of files are in format id_yyyyMMdd.pdf, where id is some number, id of file , and id is always unique, yyyyMMdd are date in format year,month,day.
Now in program i get id and i need to find file with that id, then check date when file is created , and if there are new version of file(blob in database) i need to write this new file to disk and than open it, if this is last version of file i need just open.(i have PDFs like blob, and i need to check is on hard disk last version file.) I know how to write pdf from blob to file i cannot find way to open(or find) file with part of name , and thaen get second part(date) to compare it.
Any suggestions?
Sample:
on hard disk i have files:
c:\temp\12345_20140508.pdf
c:\temp\12346_20140508.pdf
In database table i have
id(12345) date(08-MAY-2014) and pdf1 file like blob.
id(12346) date(10-MAY-2014) and pdf2 file like blob.
Now in program I select id "12345" because dates are same i need to open file 12345_20140508.pdf
When i get select id 12346 i need first get file file from database because date in database is newer than date on hard disk, remove file 12346_20140508.pdf and save new file like 12346_20140510.pdf and than open.
If it is need i can change format of name.
I supposed the main problem you met is "how to find the newest file by id". So may be you can try this code. It can find the last created file start with some id. Once you get the file, I thought other things won't be a problem to you.
var directoryInfo = new DirectoryInfo(#"c:\temp");
var latestFile = directoryInfo.GetFiles()
.Where(f => f.Name.StartsWith("12345_"))
.OrderByDescending(f => f.CreationTime)
.FirstOrDefault();
what you should do is:
string searchPattern = "what you want to open";
File.Open(Directory.GetFiles(#"c:\", searchPattern + "*").First());
That will open the file in the c# sense,
however to open in an app use
Process.Start("notepad.exe", Directory.GetFiles(#"c:\", searchPattern + "*").First());
if you want to open them all wrap this in a foreach
foreach (var file in Directory.GetFiles(#"c:\", searchPattern + "*"))
{
//do stuff
}
Related
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")
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);
}
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";
I am trying to get a file path to a file where the file name keep changing. So far, I have a file path to a particular log file named 18052015.log. I am specifying the file name and extension, 18052015.log.
string strFilePath = #"\\server-1\public\logs\18052015.log";
The file name matches a date. Each day a new file is generated. So, tomorrow there will be a file named 19052015.log
The only file I'm interested in retrieving is the one named date.log as in 18052015.log or 19052015.log. I cannot use the option to just retrieve any log with a .log extension, as there are many other files in the same logs folder, all with the file extension .log e.g AFile.log, BFile.log, 1File.log, 2File.log. So, the following code doesn't help.
string[] files = Directory.GetFiles(strFilePath, "*.log", SearchOption.AllDirectories);
My question is, how, if the name of the file changes daily, can I retrieve that one log without specifying it's name?
I think you're looking for DateTime.Now in a specified format:
string directoryPath = #"\\server-1\public\logs;"
string fullLogPath = string.Format(#"{0}\{1:ddMMyyyy}.log", directoryPath, DateTime.Now);
To combine all solutions:
string fullFilename = Path.Combine( #"\\server-1\public\logs", string.Format("{0:ddMMyyyy}.log", myTime) );
And to correctly use Path.Combine instead of string'formatting around :-)
Use DateTime
Here is a little example:
DateTime myTime = DateTime.Now;
string fileName = string.Format("{0}{1}{2}.log", myTime.Date, myTime.Month, myTime.Year);
DateTime.Now gives you the Time from your computer. then you can extract the Date, Month and Year from the Struct.
I have a C# console application that uses text from a txt file as a parameter for a SQL query. After the query runs, it stores the highest primary key in the text file. The next time it runs, it uses the first line of that text file in the WHERE statement to grab primary keys higher than the previously stored one. Here's the code I'm using:
// get latest primary key
static String mostRecentID= File.ReadAllLines(#"C:\DataStorage\latestID.txt").First().Trim();
// run the query
SELECT * FROM whatever WHERE pk > mostRecentID
// store latest primary key
DataRow mostRecentIDRow= exportTable.Select().FirstOrDefault();
if (mostRecentIDRow!= null)
{
mostRecentID = mostRecentIDRow[0].ToString().Trim();
File.WriteAllLines(#"C:\DataStorage\latestID.txt", new String[] { mostRecentID});
}
I need to be able to read and write to this text file independent of where the program or the file is located. Is there a way to do this while keeping it in the release folder of the program?
Just use this variable:
string myDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
to get the directory where you program executes.
So when you place your .txt in Release Folder you can use:
File.WriteAllLines(myDirectory + "/" + "latestID.txt", new String[] { mostRecentID});
If you are trying to keep the text file in the root location of the application use this
string file = Path.Combine(
System.Reflection.Assembly.GetExecutingAssembly().Location, "latestID.txt");
you can get the path of the current running assembly like this:
string path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
and there you can save/load your file