Delete files, copy the same named files from another folder C# - c#

I have several issues within a windows forms application. So far, I have managed to loop though a folder and display the reuslts in a text box. Once these have returned, the user can check the results and the error files can be removed using the following;
private void button2_Click(object sender, EventArgs e)
{
foreach (string file in Directory.GetFiles(#"\\" + textBox1.Text + #"\\d$\\NSB\\Coalition\\EDU", "*.err").Where(item => item.EndsWith(".err")))
{
File.Delete(file);
}
}
What I want to do now, after the error files have been removed, is copy the same files from a backup folder (the only difference in the filenames is the file extention) I am using a seperate button for this action. Any help on this final step would be greatly appreciated.

Use Path class to get File names without extensions, combine paths and more, as an example:
StringCollection filesToBeReplaced = new StringCollection();
private void button2_Click(object sender, EventArgs e)
{
foreach (string file in Directory.GetFiles(#"\\" + textBox1.Text + #"\\d$\\NSB\\Coalition\\EDU", "*.err").Where(item => item.EndsWith(".err")))
{
//Now you have file names without extension
filesToBeReplaced.Add(Path.GetFileNameWithoutExtension (file));
File.Delete(file);
}
}
private void CopyGoodFilesFromSource()
{
foreach(string fileName in filesToBeReplaced)
{
string sourceFilePath = Path.Combine("YOUR FOLDER FOR GOOD FILES",
Path.ChangeExtension(fileName,"Your Extension")) ;
string destinationPath = Path.Combine("Destination Folder",
Path.ChangeExtension(fileName, "Your Extension in destination folder");
File.Copy(sourceFilePath , destinationPath, true);
}
}

Related

How to list the search files into listbox by date modified using C#?

Here i have a problem with to list the search files into the listbox according to the date modified. The below code is shows only list the search files into the listbox. Could anyone help me how settle this problem please.....
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string search = TextBox1.Text; // here type the folder name
if (search != "")
//DirectoryInfo d = new DirectoryInfo(#"\\192.123.1.18\Report\Result" + search);
{
string[] files = Directory.GetFiles(#"\\192.123.1.16\Report\Result\"+ search, "*.txt", SearchOption.AllDirectories);
foreach (string file in files)
{
//ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));
ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file)); // listed all files in the search folder
}
{
search = "";
}
}
else
{
Response.Write("<script>alert('Please Enter Search Keyword');</script>");
}
}
For every file you can call: File.GetLastWriteTime and after that you sort this file list according to last write datetime.
Follow below article for more information.
https://msdn.microsoft.com/en-us/library/d5da1572.aspx
First create one class with name FileModifiedDate
Add to properties in this 1.Filename , 2.ModifiedDate and 3.File.
List<FileModifiedDate> FileList=new List<FileModifiedDate>();
foreach (string file in files)
{
//ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));
// ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file)); //
FileModifiedDate FileInfo=new FileModifiedDate();
FileInfo.FileName=Path.GetFileName(file);
FileInfo.File=file;
FileInfo.ModifiedDate=File.GetLastWriteTime(path);
FileList.Add(FileInfo);
}
FileList=FileList.OrderByDescending(a=>a.ModifiedDate).ToList();
foreach (FileModifiedDate SingleFile in FileList)
{
//ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));
ListBox1.Items.Add(new ListItem(SingleFile.FileName, SingleFile.file)); //
}
For every file you can call: FileInfo.LastWriteTimeUtc and after that, you should sort this file list according to their last write DateTime. DateTime class implements compasion operators so that you won't have trouble while sorting

How to open a jpg file with your application?

I am developing an application and I need to read the EXIF details of JPG file.
I am able to do so with an OpenFileDialog button but, I want it to be so that a user can open a JPG file with my application (right click>Open with) and I could get the path of the JPG file in string.
I just want to know how to get the path of the file on which the user right clicked ad selected open with "My Application"
You need to register your application for the JPG file extension in the Registry as described here: https://msdn.microsoft.com/en-us/library/windows/desktop/cc144175(v=vs.85).aspx
If you know how to get the EXIF data already and just want users to be able to right-click a JPG file > Open with > Select your application and then get the filename they're trying to open, you can do this:
private void testButton_Click(object sender, EventArgs e)
{
string[] cmdLineArgs = Environment.GetCommandLineArgs();
string jpgFilenameToOpen = "None";
if (cmdLineArgs.Length > 1)
{
jpgFilenameToOpen = cmdLineArgs[1];
}
YourGetEXIFDetailsMethod(jpgFilenameToOpen);
}
The Environment.GetCommandLineArgs() returns an array with all command line arguments that was passed to your application on load. Normally, if they just pass a filename, it should be the 2nd item in the array.
You can also loop through the arguments if needed by doing this:
foreach (var arg in cmdLineArgs)
{
MessageBox.Show(arg.ToString());
}
Edit:
I just realized I'm not sure if you need to accept only one JPG filename at a time or if you need to accept multiple JPG files at once. If it's the latter, here's some updated code that can loop through all the command-line arguments and do something with only JPG/JPEG files:
private void Form1_Load(object sender, EventArgs e)
{
string[] cmdLineArgs = Environment.GetCommandLineArgs();
List<string> jpgFilenamesToAnalyze = new List<string>();
foreach (var arg in cmdLineArgs)
{
if (arg.Contains(".jpg") || arg.Contains(".jpeg"))
{
jpgFilenamesToAnalyze.Add(arg);
}
}
if (jpgFilenamesToAnalyze.Count > 0)
{
StringBuilder sbJPGFiles = new StringBuilder();
sbJPGFiles.AppendLine("Found " + jpgFilenamesToAnalyze.Count + " images to analyze:\n\nFiles:");
foreach (var jpgFilename in jpgFilenamesToAnalyze)
{
// YourGetEXIFDataMethod(jpgFilename)
sbJPGFiles.AppendLine(jpgFilename);
}
MessageBox.Show(sbJPGFiles.ToString());
}
else
{
MessageBox.Show("No images found to analyze");
}
}

ExtractToFile vs ExtractToDirectory

I have some code that is extracting a file to a directory. In the code below Global.fullpath is the full path to the file its self where as Global.path is the path to the directory. This code works:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
AppendTextBox("Extracting Files...\r\n");
ZipFile.ExtractToDirectory(Global.fullPath, Global.path);
}
However I am trying to do an overwrite if any files exist so I have this code which doesn't seem to extract anything even when there are no existing files:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
AppendTextBox("Extracting Files...\r\n");
using (ZipArchive archive = ZipFile.OpenRead(Global.fullPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
AppendTextBox("Extracting file: " + entry.FullName + "...\r\n");
entry.ExtractToFile(Path.Combine(Global.path, entry.FullName), true);
}
}
}
Based on the comments, if you're trying to extract a directory ExtractToFile() is not going to do what you expect. Directories can't be easily overwritten like files. I think you have two options:
Check if the directory specified by FullName exists, and delete it before writing.
Check if the directory specified by FullName exists, and then rename your folder you're going to write something like FullName = FullName + "_Copy";
Make sure you check if the combined path is a valid filename. The ExtractToFile method expects a path that ends with the filename, and some Zip archives can contain folders. In such a case, the entry.FullName property results in an invalid path.

Dynamic File Paths

Suppose I had a particular directory on C# in the following format:
#"C:\blabla\bla\0.0.1.63\blabla.png";
The "0.0.1.63" changes occasionally due to updates to the software and so on.
I want to know how I can assign a "..\" - similar effect for that particular directory to be dynamic. Because I do not know the update sequence.
So, how do I make it so that the directory stays the same, while that particular part of the directory (0.0.1.63) is an "unknown" directory.
You can use the DirectoryInfo.EnumerateDirectories and the DirectoryInfo.EnumerateFileSystemInfos methods to find your file, you could then strip the filename from the FileInfo objects FullName and use the result. Something like this should work.
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = getPath();
openFileDialog1.ShowDialog();
}
private string getPath()
{
DirectoryInfo di = new DirectoryInfo(#"C:\blabla\bla\");
foreach (var d in di.EnumerateDirectories())
{
foreach(var fi in d.EnumerateFileSystemInfos())
{
if (fi.Name == "blabla.png")
{
return fi.FullName.Replace(fi.Name,"");
}
}
}
return di.FullName ;
}

load selected .txt file from datagridview and open the file in listview c#

so basically i have a data grid view that goes into a file and loads all of the .txt file names into a data grid view. What i need to do is when i click on a certain file in data grid view, it will open up the contents of that file into a list view.
Can anyone help as i am stuck?
I am guessing its something like:
if data grid view value = .txt file in the folder then load contents into listview.
sounds easy enough just unsure how to code this.
Thank you
I have this so far but still does not work:
private void gridProfiles_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (gridProfiles.Rows[e.RowIndex].Cells[0].Value != null)
{
var path = gridProfiles.Rows[e.RowIndex].Cells[0].Value.ToString();
path = Path.Combine(rootDirectory + "\\Profiles\\", path);
if (File.Exists(path))
{
String[] lines = File.ReadAllLines(path);
foreach (var line in lines)
{
lstProcesses.Items.Add(path);
}
}
}
}
When i run this it gets ti if(file.exists(path) and then skips over it
route directory:
private static string rootDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\My File";
static void CreateDirectory()
{
string rootDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\My File";
if (!Directory.Exists(rootDirectory)) { Directory.CreateDirectory(rootDirectory); }
if (!Directory.Exists(rootDirectory + "\\Profiles")) { Directory.CreateDirectory(rootDirectory + "\\Profiles"); }
Looks like you create incorrect path, or you are reading incorrect cell value. Use overloaded Path.Combine which accept list of path parts. Also instead of adding path to list you should add line.
Following code will show you error message if file not exist with path where it tries to look for file. Also it will show error message if there is no file name in grid cell.
private void gridProfiles_CellClick(object sender, DataGridViewCellEventArgs e)
{
object value = gridProfiles.Rows[e.RowIndex].Cells[0].Value;
if (value == null)
{
MessageBox.Show("Cannot get file name from grid");
return;
}
var file = value.ToString();
var path = Path.Combine(rootDirectory, "Profiles", file); // create path
if (!File.Exists(path))
{
MessageBox.Show(path + " not found");
return;
}
foreach(string line in File.ReadLines(path))
lstProcesses.Items.Add(line); // add line instead of path
}

Categories