Append timestamp to csv file in c# - c#

I am trying to generate unique csv files by appending timestamps at the end of the file name.
But for some reason csv file is not generating.
String path= #"C:\\Users\Isuruh\source\repos\WindowsService1\WindowsService1\bin\Debug\data.csv";
FileInfo info = new FileInfo(path);
bool exists = info.Exists;
library.WriteErrorLog(exists.ToString());
// Upload data from file
--> string result = "data_" + DateTime.Now.ToFileTime() + ".csv";
if(exists == true)
{
File.Delete(Path.GetFileName(path));
sqlRun();
File.WriteAllText(#"C:\\Users\Isuruh\source\repos\WindowsService1\WindowsService1\bin\Debug\**result**", csv.ToString());
}
else
{
sqlRun();
File.WriteAllText(#"C:\\Users\Isuruh\source\repos\WindowsService1\WindowsService1\bin\Debug\**result**", csv.ToString());
}
}

I think you have forgotten to combine the folder path and the expected filename
Here goes your code refactored (not tested):
var folder = #"C:\\Users\Isuruh\source\repos\WindowsService1\WindowsService1\bin\Debug\";
var path = Path.Combine(folder, "data.csv");
FileInfo info = new FileInfo(path);
bool exists = info.Exists;
library.WriteErrorLog(exists.ToString());
// Upload data from file
var result = "data_" + DateTime.Now.ToFileTime() + ".csv";
var fullResultPath = Path.Combine(folder, result);
if(exists)
{
// Do you really want to delete the data.csv file ?
File.Delete(path);
}
sqlRun();
File.WriteAllText(fullResultPath, csv.ToString());

Related

System.NotSupportedException: 'The specified path format is not supported.'

I have a field in a table that needs to be filled with the path and the end of the XML file to create a new file in the directory called DONE. This is made so it can tidy the directory a bit since the ones that are done don't need to be in the same directory so they are copied from one place into another.
Why is there this error?
System.NotSupportedException: 'The specified path format is not supported.'
Console.WriteLine("Ficheiro processado: " + filename);
string rootFolderPath = #"C:\XMLFiles";
string destinationPath = #"C:\XMLFiles\DONE";
string[] fileList = Directory.GetFiles(rootFolderPath);
foreach (string file1 in fileList)
{
string fileToMove = rootFolderPath + file1;
string moveTo = destinationPath + file1;
File.Move(fileToMove, moveTo);
da.SP_Insert(filename, file.Name, batch.BatchClassName, batch.Name, batch.Description, 0, "", 1, moveTo );
}
The function Directory.GetFiles(rootFolderPath); returns the full path to the file, that is filename and directory. If, like you are trying, want the filename only, you will need to extract it.
The FileInfo class is very good at extracting the Filename only of a full path.
foreach (string file1 in fileList)
{
FileInfo fi = new FileInfo(file1);
string moveTo = Path.Combine( destinationPath, fi.Name);
File.Move(file1, moveTo);
}
Rather than using string fileToMove = rootFolderPath + file1, try using System.IO.Path.Combine instead:
var fileToMove = Path.Combine(rootFolderPath, file1);
var moveTo = Path.Combine(destinationPath , file1);
GetFiles returns full paths; not just filenames:
Returns the names of files (including their paths) in the specified directory
So for the source files you don't need to combine anything, and for the target path you need to split off the filename first before combining:
foreach (string file1 in fileList)
{
string moveTo = Path.Combine(destinationPath, Path.GetFileName(file1));
File.Move(file1, moveTo);
// ...
}
This Problem was fixed this way.
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string CaminhoInicial = openFileDialog1.FileName;
Guid g = Guid.NewGuid();
FileInfo fi = new FileInfo(CaminhoInicial);
File.Copy(CaminhoInicial, CaminhoFinal + g.ToString() + fi.Extension, true);
da.SP_Inserir_Imagem(id, g.ToString() + fi.Extension);
}
}
try
{
if (dt.Rows.Count != 0)
{
string NomeImagem = dt.Rows[0][0].ToString();
pictureBox1.Image = Image.FromFile(CaminhoFinal + NomeImagem.Replace(" ", ""));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " |||| " + ex.StackTrace, "Erro", MessageBoxButtons.OK);
}
Also read this Microfost Docs post for more context.
https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=net-5.0

Extract zip file and overwrite (in the same directory - C#)

I'm starting some C# stuff, and i would like to extract and force to overwrite all files from a zip archive. I know that there are many other solution in Stack, but nothing works for me :/
i've tried this method:
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, extractPath);
return (0); // 0 all fine
}
catch (Exception)
{
return (1); // 1 = extract error
}
This extractor works fine, but doesn't allow me to overwrite files meanwhile extraction, and it returns error and exceptions ... i've tried to take a look at MS-Documention, without success ...
someone know how does it work ?
Try something like this. Away from my dev box so this may require some tweaking, just writing it from memory.
Edit: As someone mentioned you can use ExtractToFile which has an overwrite option. ExtractToDirectory does not.
Essentially you unzip to a temporary folder then check if an unzipped file's name already exists in the destination folder. If so, it deletes the existing file and moves the newly unzipped one to the destination folder.
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
//Declare a temporary path to unzip your files
string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, tempPath);
//build an array of the unzipped files
string[] files = Directory.GetFiles(tempPath);
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath,f.Name)))
{
File.Delete(Path.Combine(extractPath, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
}
//Delete the temporary directory.
Directory.Delete(tempPath);
return (0); // 0 all fine
}
catch (Exception)
{
return (1); // 1 = extract error
}
Edit, in the event directories are unzipped (again, may need to be tweaked, I didn't test it):
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
//Declare a temporary path to unzip your files
string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, tempPath);
//build an array of the unzipped directories:
string[] folders = Directory.GetDirectories(tempPath);
foreach (string folder in folders)
{
DirectoryInfo d = new DirectoryInfo(folder);
//If the directory doesn't already exist in the destination folder, move it to the destination.
if (!Directory.Exists(Path.Combine(extractPath,d.Name)))
{
Directory.Move(d.FullName, Path.Combine(extractPath, d.Name));
continue;
}
//If directory does exist, iterate through the files updating duplicates.
else
{
string[] subFiles = Directory.GetFiles(d.FullName);
foreach (string subFile in subFiles)
{
FileInfo f = new FileInfo(subFile);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath, d.Name, f.Name)))
{
File.Delete(Path.Combine(extractPath, d.Name, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, d.Name, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, d.Name, f.Name));
}
}
}
}
//build an array of the unzipped files in the parent directory
string[] files = Directory.GetFiles(tempPath);
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath,f.Name)))
{
File.Delete(Path.Combine(extractPath, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
}
Directory.Delete(tempPath);
return (0); // 0 all fine
}

Why is File.Move not working as expected?

I am trying to move all files from rootFolderPath to destinationPath
try
{
string rootFolderPath = #"D:\Log_siteq\";
if (!Directory.Exists(Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString())))
{
System.IO.Directory.CreateDirectory(Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString()));
}
string destinationPath = Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString() );
string fileTypes = #"*.*";
string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, fileTypes);
foreach (string file in fileList)
{
string ext = Path.GetExtension(file);
string destination = Path.Combine(destinationPath,file);
File.Move( file,destination);
MessageBox.Show(file);
MessageBox.Show(destination);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
Apparently MessageBox.Show(file); shows me my root folder path ( as is normal) but MessageBox.Show(destination); is showing me the same thing.
What gives? It just moves my file from my root folder in the same folder.Am I not getting something?
You are combining the destinationPath with the complete file path of file:
string destination = Path.Combine(destinationPath, file);
which will just overwrite the destination with the original file path (because "C:\desitnation\C:\source\filename.txt" isn't a valid path).
Instead, you need only the file name like this:
string destination = Path.Combine(destinationPath, Path.GetFileName(file));

How to replace an image with same name but different type of another image in a folder?

Suppose i have a folder and in this folder is an image named im1.png. i want that im1.png is deleted when i save another image named im1.jpg or im1.bmp or so on...(same name but different type) in this folder. i write following code but this code just delete file that has same name and same type. Help me please...
string CopyPic(string MySourcePath, string key, string imgNum)
{
string curpath;
string newpath;
curpath = Application.Current + #"\FaceDBIMG\" + key;
if (Directory.Exists(curpath) == false)
Directory.CreateDirectory(curpath);
newpath = curpath + "\\" + imgNum + MySourcePath.Substring(MySourcePath.LastIndexOf("."));
string[] similarFiles = Directory.GetFiles(curpath, imgNum + ".*").ToArray();
foreach (var similarFile in similarFiles)
File.Delete(similarFile);
File.Copy(MySourcePath, newpath);
return newpath;
}
Here is one way to do it:
string filename = ...; //e.g. c:\directory\filename.ext
//Get the directory where the file lives
string dir = Path.GetDirectoryName(filename);
//Get the filename without the extension to use it to search the directory for similar files
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(filename);
//Search the directory for files with same name, but with any extension
//We use the Except method to remove the file it self form the search results
string[] similarFiles =
Directory.GetFiles(dir, filenameWithoutExtension + ".*")
.Except(
new []{filename},
//We should ignore the case when we remove the file itself
StringComparer.OrdinalIgnoreCase)
.ToArray();
//Delete these files
foreach(var similarFile in similarFiles)
File.Delete(similarFile);

Check Zip File content and extract

Hi I want to extract a ZipFile that has various of text files. But i could be that de text files are in a folder. So what i want to do is: If an folder exists just exract normaly if not create a folder with name of ZipFile. The reason is i don't want to have a folder in a folder with the same name.
My Previous Code:
foreach (string file in newZips) {
FileInfo fileInfo = new FileInfo(file);
string dirName = newPath + "\\" + fileInfo.Name.Substring(0, fileInfo.Name.Length - 4);
Console.WriteLine(dirName);
Directory.CreateDirectory(dirName);
ZipFile.ExtractToDirectory(allZipsPath + "\\" + fileInfo.Name, dirName);
}
Maybe this helps you:
string path = #"C:\..\..\myFolder";
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Thats how you can check a path if it contains the Folder you expect. And if not it creates that Folder!
--- EDIT (if unknown zip-Name) ---
string myPathToZip = #"C:\..\..\folderName";
foreach (string file in Directory.GetFiles(myPathToZip, "*.zip", SearchOption.AllDirectories))
{
//the current path of the zipFile (with the Name included)
var path = new FileInfo(file.ToString());
//The filename
var filename = Path.GetFileName(file.ToString()).Replace(".zip", "");
}

Categories

Resources