DateTime stamp in output .zip file - c#

I have a String Path to output a .ZIP file String path = #"C:\TEMP\test.zip"; and I am looking to five the file name a date stamp. Example, test_TodayDate.ZIP.
There's a way to achieve this?
Thanks

You can create your own variable, like this,
// gets the file name without extension
var fileName = Path.GetFileNameWithoutExtension(path);
// create the new file name
var newFileName = fileName + "_" + DateTime.Now + ".zip";
Now save the new file generated, and name this file as the newFileName it will have the DateTime in the name.

You can do:
string filePath = #"C:\TEMP\test.zip";
string finalPath = Path.Combine(Path.GetDirectoryName(filePath),
Path.GetFileNameWithoutExtension(filePath)
+ DateTime.Now.ToString("yyyyMMddHHmmss")
+ Path.GetExtension(filePath));
First Get File name without extension and add your Time Stamp, Then concatenate file extension,
Then get Current directory for the file path
Use Path.Combine to combine directory and new file name

Related

Renaming a file using file.move, but adding a string for every new text

Beginner coder here.
I need to add the GetLastWriteTime string to my filename using the (rename) file.move method. How do I add a string using file.move?
I've looked up some similar info, and I've gotten part of the answer I need. System.IO.File.Move("oldfilename", "newfilename"); is the code I'll need help with. I tried adding a string to the newfilename, but it only supports directory.
string[] files = Directory.GetFiles("C:/foto's", "*", SearchOption.TopDirectoryOnly);
string filename = Path.GetFileName(photo);
DateTime fileCreatedDate = System.IO.File.GetLastWriteTime(filename);
System.IO.File.Move(#"C:\foto's", #"C:\foto's" + fileCreatedDate);
Expected error, string cannot be accepted in a directory place.
I've always preferred to use FileInfo objects for stuff like this as they have the dates built in, have MoveTo rather than using the static File.Move etc ...
FileInfo[] fis = new DirectoryInfo(#"C:\foto's").GetFiles("*", SearchOption.TopDirectoryOnly);
foreach(FileInfo fi in fis){
//format a string representing the last write time, that is safe for filenames
string datePart = fi.LastWriteTimeUtc.ToString("_yyyy-MM-dd HH;mm;ss"); //use ; for time because : is not allowed in path
//break the name into parts based on the .
string[] nameParts = fi.Name.Split('.');
//add the date to the last-but-one part of the name
if(nameParts.Length == 1) //there is no extension on the file
nameParts[0] += datePart;
else
nameParts[nameParts.Length-1] += datePart;
//join the name back together
string newName = string.Join(".", nameParts);
//move the file to the same directory but with a new name. Use Path.Combine to join directory and new file name into a full path
fi.MoveTo(Path.Combine(fi.DirectoryName, newName));
}
Directory.Move(#"c:\foto's", #"c:\photos"); //fix two typos in your directory name ;)

Return file located in a specific path

I wrote a method in order to return a file using the return type HttpResposeMessage. I use the below code in order to attach the file.
file.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = newFileName
};
file.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return file;
How can I specify a specific path in to the filename.
I did something like this
fileName = "C://Templates/Order.pdf"
But this renames the file name as C:_Templates_Order.pdf
What I need is to go through the path and grab the file.
You can declare a string literal by using the # symbol in front of the quotes for your string:
fileName = #"C:\templates\order.pdf"
Or you can double escape the backslash
fileName = "C:\\templates\\order.pdf"
You need to put the file name using this simbol \ instead of /
fileName = "C:\\Templates\\Order.pdf";

Get File Extension C#

I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following
string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);
In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?
Things I have
1.) File name without extension in
string filename = ddl.SelectedItem.Text;
2.) Path where the file is located
string path = "F:\\WorkingCopy\\files\\" + filename
I am trying to get the file extension with these . Can any one suggest on this?
You can use Directory.EnumerateFiles() like this:
string path = "F:\\WorkingCopy\\files\\";
string filename = ddl.SelectedItem.Text;
string existingFile = Directory.EnumerateFiles(path, filename + ".*").FirstOrDefault();
if (!string.IsNullOrEmpty(existingFile))
Console.WriteLine("Extension is: " + Path.GetExtension(existingFile));
Directory.EnumerateFiles searches the path for files like filename.*. Path.GetExtension() returns the extension of the found file.
In general, I prefer to use EnumerateFiles() instead of GetFiles because it returns an IEnumerable<string> instead string[]. This suggests that it only returns the matching files as needed instead searching all matching files at once. (This doesn't really matter in your case, just a general note).
Use the Directory.GetFiles() method. Something like this
string[] files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename+".*");
This should get you an array of filenames with the same filename but different extensions. If you have only one, then you can always use the first one.
You can use Directory.GetFiles Method:
string result = Directory.GetFiles(path, filename + ".*").FirstOrDefault();
see here
here " * " is the WildCard and will search for the Filename starts with YourFileName.
you can achieve that with followed by line
try
{
var extensions = new List<string>();
var files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename + ".*", System.IO.SearchOption.TopDirectoryOnly);
foreach (var tmpfile in files)
extensions.Add(Path.GetExtension(tmpfile));
}
catch (Exception ex)
{
throw ex;
}
will this help you?
You can simply split them by dot, For example, try this code
string folder = #"F:\\WorkingCopy\\files\\";
var files = System.IO.Directory.GetFiles(folder, filename + ".*");
if (files.Any())
{
string ext = System.IO.Path.GetExtension(files.First()).Substring(1);
}
This code gives me result that the extension for this is txt file.

Searching file name with * regular expression in C#

I have a list of files in WP7 isolated storage which has space character in the file name e.g. "My File Name 1.dat". I want to get all these files name in a string[]. I have used the following code but I am not getting the file names:
string searchPattern = "FolderName" + "\\*";
string[] fileList = store.GetFileNames(searchPattern);
Please help!
Take the quotes off of your FolderName variable to make it:
string searchPattern = FolderName + "\*";

How to get only directory name from SaveFileDialog.FileName

What would be the easiest way to separate the directory name from the file name when dealing with SaveFileDialog.FileName in C#?
Use:
System.IO.Path.GetDirectoryName(saveDialog.FileName)
(and the corresponding System.IO.Path.GetFileName). The Path class is really rather useful.
You could construct a FileInfo object. It has a Name, FullName, and DirectoryName property.
var file = new FileInfo(saveFileDialog.FileName);
Console.WriteLine("File is: " + file.Name);
Console.WriteLine("Directory is: " + file.DirectoryName);
The Path object in System.IO parses it pretty nicely.
Since the forward slash is not allowed in the filename, one simple way is to divide the SaveFileDialog.Filename using String.LastIndexOf; for example:
string filename = dialog.Filename;
string path = filename.Substring(0, filename.LastIndexOf("\"));
string file = filename.Substring(filename.LastIndexOf("\") + 1);

Categories