Deleting .png File through ListView - c#

I am making an application for personal use that will organize .png files and will let me remotely delete them from the directory through the application (through a ListView).
I have a snippet that will delete the file from the ListView, but not from the actual file directory. I want to be able to do both when I click delete.
private void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (MessageBox.Show("This will delete the file from the folder. Are you sure?", "Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes)
for (int i = fileDisplayListView.SelectedItems.Count - 1; i >= 0; i--)
{
ListViewItem item = fileDisplayListView.SelectedItems[i];
fileDisplayListView.Items[item.Index].Remove();
File.Delete(fbd.SelectedPath + fileDisplayListView.Items.ToString());
}
}
Additional snippet for more information..
private void openToolStripButton_Click(object sender, EventArgs e)
{
fbd.ShowDialog();
DirectoryInfo di = new DirectoryInfo(fbd.SelectedPath);
directoryPath.Text = "Directory: " + fbd.SelectedPath;
FileInfo[] Files =
di.GetFiles("*.PNG*", SearchOption.AllDirectories);
if (Files.Length == 0)
MessageBox.Show("No .png files found in directory...", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Question);
fileDisplayListView.Items.Clear();
foreach (FileInfo f in Files)
{
ListViewItem item = new ListViewItem(f.Name);
this.fileDisplayListView.Items.Add(f.Name);
}
this.fileDisplayListView.View = View.Details;
this.fileDisplayListView.Refresh();
}
The last part of it, File.Delete(fbd.SelectedPath + fileDisplayListView.Items.ToString());
is not functional. Please help!

This code gets a list of all .jpg files in the directory, adds them to the ListView. By pressing the button it deletes the selected ListView elements and files:
private FileInfo[] files;
public Form1()
{
InitializeComponent();
files = new DirectoryInfo(#"C:\Users\User\Pictures").GetFiles("*.jpg", SearchOption.AllDirectories);
foreach (var file in files)
{
listView1.Items.Add(file.Name);
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
var curentItem = listView1.SelectedItems[i];
foreach (FileInfo file in files)
{
if (curentItem.Text == file.Name)
{
listView1.Items.Remove(curentItem);
file.Delete();
i--;
}
}
}
}

This is the snippet I used to fix the application. It is a lot more directly related to how I am approaching the problem.
if (MessageBox.Show("This will delete the file from the folder. Are you sure?", "Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes)
for (int i = fileDisplayListView.SelectedItems.Count - 1; i >= 0; i--)
{
ListViewItem item = fileDisplayListView.SelectedItems[i];
string fpath = string.Empty;
fileDisplayListView.Items[item.Index].Remove();
fpath = fbd.SelectedPath.ToString() + "\\" + item.Text;
File.Delete(fpath);
}

Related

How to show message if folder contains different extensions along with my .Dat file?

I have to show a message, if my folder contains .Dat files and other
extension files. how to do this . Need help appreciated
private void btnChooseFile_Click(object sender, EventArgs e)
{
FileInfo[] files;
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.RootFolder = Environment.SpecialFolder.MyComputer;
fbd.SelectedPath = #txtFilepath.Text.Trim();
if (fbd.ShowDialog() == DialogResult.OK)
{
txtFilepath.Text = fbd.SelectedPath;
if (rbtnOffline.Checked)
{
DefaultManager.OfflineFilePath = #txtFilepath.Text.ToString().Trim();
DirectoryInfo info = new DirectoryInfo(DefaultManager.OfflineFilePath);
files = info.GetFiles("*.dat").OrderBy(p => p.LastWriteTime).ToArray();
if (files.Count() > 0)
{
// MessageBox.Show("no error");
}
else
{
MessageBox.Show("Error, Incorrect capture folder selected", "PGY-SSM", MessageBoxButtons.OK, MessageBoxIcon.Error);
//txtFilepath.Clear();
}
}
else
{
DefaultManager.DumpFilePath = #txtFilepath.Text.ToString().Trim();
}
}}
To determine if there are any other files in the folder, compare the total number of files in the folder with the number of dat files:
int fileCount = info.GetFiles().Length;
int datFileCount = info.GetFiles("*.dat").Length;
if (fileCount != datFileCount)
{
MessageBox.Show("Error, other files found …");
}

Checkedlistbox refresh not working

I have this method to open and fill checkedlistbox.
void Show_files()
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog() == DialogResult.OK)
{
checkedListBox1.Items.Clear();
string[] files = Directory.GetFiles(FBD.SelectedPath);
string[] dirs = Directory.GetDirectories(FBD.SelectedPath);
foreach (string file in files)
{
checkedListBox1.Items.Add(file);
}
foreach (string dir in dirs)
{
checkedListBox1.Items.Add(dir);
}
}
}
and then button to delete selected files.
private void button1_Click(object sender, EventArgs e)
{
foreach (var item in checkedListBox1.CheckedItems.OfType<string>().ToList())
{
DialogResult dialogResult = MessageBox.Show("Czy na pewno chcesz usunać zaznaczone pliki", "Czy na pewno chcesz usunać zaznaczone pliki?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
File.Delete(item);
}
}
MessageBox.Show("Usunięto");
checkedListBox1.Refresh(); // here should refresh list of folder content
}
I've tried to clear and add items again in loop (if items count not null) in method Show_files() but it hasn't worked. Hide and show neither. I don't want to open folder browser again. It has to happen automatically.
You aren't removing the item from the control:
if (dialogResult == DialogResult.Yes)
{
File.Delete(item);
checkedListBox1.Items.Remove(item);
}
Best to put some Try...Catch blocks around such operations.

Loading large amount of text files from a share drive to search for a world. C#

Im trying to perform a search in a share drive that contains at least 90,000 files.
The code below is what I have:
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("No folder: Not listed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
List<string> allFiles = new List<string>();
AddFilesnames(sourceFolder, allFiles);
foreach (string fileName in allFiles)
{
string contents = File.ReadAllText(fileName);
if (contents.Contains(searchword))
{
listBox1.BeginUpdate();
listBox1.Items.Add(fileName);
listBox1.EndUpdate();
label4.Text = (Convert.ToInt32(label4.Text) + 1).ToString();
}
}
if (listBox1.Items.Count == 0)
{
MessageBox.Show("no files");
}
}
}
public void listboxtofile()
{
DialogResult resDialog = dlgSaveFile.ShowDialog();
if (resDialog.ToString() == "OK")
{
FileInfo fi = new FileInfo(dlgSaveFile.FileName);
StreamWriter sw = fi.CreateText();
foreach (string sItem in listBox1.Items)
{
sw.WriteLine(sItem);
}
sw.Close();
}
}
public void AddFilesnames(string sourceDir, List<string> allFiles)
{
string[] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
DateTime from1 = dateTimePicker1.Value.Date;
DateTime to1 = dateTimePicker2.Value.Date;
DateTime creationTime = File.GetCreationTime(fileName);
if (creationTime >= from1 && creationTime <= to1)
{
allFiles.Add(fileName);
}
}
//Recursion
string[] subdirectoryEntries = Directory.GetDirectories(sourceDir);
foreach (string item in subdirectoryEntries)
{
// Avoid "reparse points"
if ((File.GetAttributes(item) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
AddFileNamesToList(item, allFiles);
label4.Text = (Convert.ToInt32(label4.Text) + 1).ToString();
}
}
}
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
textBox1.Clear();
}
private void button5_Click(object sender, EventArgs e)
{
listboxtofile();
}
}
}
So far this is working with 3,000 files but I need to have access to a shared drive that contains 90,000 files and when I try to search in the share drive the windows form get frozen. I will really apreciate any help from you all.
My suggestion would be to do any file system work in a separate thread. If you do the file searching in the same thread as your form, Windows has no chance to update the form. You won't be able to update any of your form controls (like listBox1) directly from the new thread, but you can look into delegates and C# threading in general for ways to work around this.
Also, if you just need to search files for a specific word, have you looked into existing tools like grep?

listbox drag and drop items, items name

I have some function
private void listBox2_Drop(object sender, System.Windows.DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(System.Windows.DataFormats.FileDrop, false);
for (int i = 0; i < files.Length; i++)
{
ListItemEl el = new ListItemEl();
el.ui = files[i];
listBox2.Items.Add(el);
}
}
the row:
(string[])e.Data.GetData(System.Windows.DataFormats.FileDrop, false)
return file location.
Which function returns me from DragEventArgs name of file?
You already have the full path just get the filename with Path.GetFileName
var files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (var filename in files)
{
var nameOnly = System.IO.Path.GetFileName(filename);
}

How can I load a folders files into a ListView?

I'd like to have a user select a folder with the FolderBrowserDialog and have the files loaded into the ListView.
My intention is to make a little playlist of sorts so I have to modify a couple of properties of the ListView control I'm assuming. What properties should I set on the control?
How can I achive this?
Surely you just need to do the following:
FolderBrowserDialog folderPicker = new FolderBrowserDialog();
if (folderPicker.ShowDialog() == DialogResult.OK)
{
ListView1.Items.Clear();
string[] files = Directory.GetFiles(folderPicker.SelectedPath);
foreach (string file in files)
{
string fileName = Path.GetFileNameWithoutExtension(file);
ListViewItem item = new ListViewItem(fileName);
item.Tag = file;
ListView1.Items.Add(item);
}
}
Then to get the file out again, do the following on a button press or another event:
if (ListView1.SelectedItems.Count > 0)
{
ListViewItem selected = ListView1.SelectedItems[0];
string selectedFilePath = selected.Tag.ToString();
PlayYourFile(selectedFilePath);
}
else
{
// Show a message
}
For best viewing, set your ListView to Details Mode:
ListView1.View = View.Details;
A basic function could look like this:
public void DisplayFolder ( string folderPath )
{
string[ ] files = System.IO.Directory.GetFiles( folderPath );
for ( int x = 0 ; x < files.Length ; x++ )
{
lvFiles.Items.Add( files[x]);
}
}
List item
private void buttonOK_Click_1(object sender, EventArgs e)
{
DirectoryInfo FileNm = new DirectoryInfo(Application.StartupPath);
var filename = FileNm.GetFiles("CONFIG_*.csv");
//Filename CONFIG_123.csv,CONFIG_abc.csv,etc
foreach(FileInfo f in filename)
listViewFileNames.Items.Add(f.ToString());
}

Categories