listbox drag and drop items, items name - c#

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);
}

Related

Deleting .png File through ListView

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);
}

Why when adding to the listview items the result is not the file name?

I'm searching in a directory in *.cs files for specific string.
If there is a result i'm adding it to a listview.
But when it's adding the result to the listview i don't see the CS file name the string was found in but something else.
In the backgroundworker dowork event
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FindLines(#"d:\c-sharp", "simplecontextmenu");//"string s1 = treeView1.SelectedNode.Tag as string;");
}
This is the FindLines code
bool result = false;
public List<string> FindLines(string DirName, string TextToSearch)
{
int counter = 0;
List<string> findLines = new List<string>();
DirectoryInfo di = new DirectoryInfo(DirName);
List<FileInfo> l = new List<FileInfo>();
CountFiles(di, l);
int totalFiles = l.Count;
int countFiles = 0;
if (di != null && di.Exists)
{
if (CheckFileForAccess(DirName) == true)
{
foreach (FileInfo fi in l)
{
backgroundWorker1.ReportProgress((int)((double)countFiles / totalFiles * 100.0), fi.Name);
countFiles++;
System.Threading.Thread.Sleep(1);
if (string.Compare(fi.Extension, ".cs", true) == 0)
{
using (StreamReader sr = fi.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains(TextToSearch))
{
counter++;
findLines.Add(s);
result = true;
backgroundWorker1.ReportProgress(0, s);
}
}
}
}
}
}
}
return findLines;
}
And this is the backgroundworker progresschanged event
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label2.Text = e.UserState.ToString();
if (result == true)
{
listView1.Items.Add(e.UserState.ToString());
result = false;
}
}
Something with the ReportProgress in the FindLines method and with the e.UserState in the progresschanged event is wrong. I don't get the path and name of the cs file the string was found in in the listview.
I'm searching in this directory for the string "simplecontextmenu" and if the string is in any of the cs files in the directory i want to add to the listview the file name where the string was found in with the directory for example if the string was found in test.cs then in listview show me:
c:\mytest\test.cs "simplecontextmenu"
But what i get instead is the line it self from the code what i see in the listview is this: FindLines(#"d:\c-sharp", "simplecontextmenu");//"string s1 = treeView1.SelectedNode.Tag as string;");
You are reporting the matching line s in the backgroundWorker1.ReportProgress(0, s);. You should be reporting the file name instead:
backgroundWorker1.ReportProgress(0, fi.FullName);

Show selected text file from one listbox in another

This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
FileInfo SelectedFileInfo = (FileInfo)ListBox1.SelectedItem;
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
string CurrentLine = "";
//int LineCount = 0;
while(FileRead.Peek() != -1)
{
CurrentLine = FileRead.ReadLine();
//LineCount++;
//if(LineCount % 5 == 2)
{
ListBox2.Items.Add(CurrentLine);
}
}
FileRead.Close();
}
but throws exception about:
Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'System.IO.FileInfo'
When populating the listbox, use the filename instead instead the FileInfo
Then when in Button1_Click, use ListBox1.SelectedValue to get the selected file name
protected void Button1_Click(object sender, EventArgs e)
{
ListBox2.Items.Clear();
if (ListBox1.SelectedIndex > -1)
{
string filename = ListBox1.SelectedValue;
StreamReader FileRead = new StreamReader(filename);
string CurrentLine = "";
//int LineCount = 0;
while (FileRead.Peek() != -1)
{
CurrentLine = FileRead.ReadLine();
ListBox2.Items.Add(CurrentLine);
}
FileRead.Close();
}
else
{
ListBox2.Items.Add("Please select a file first");
}
}
protected void Btn_Load_Click(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\errorlog");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
ListBox1.Items.Add(file.FullName);
}
}
}

How to write all files Contain in the subfolders and in the folders in to a .txt file

the following code is reading all files Contain in the subfolders and in the folders.
But I need to write all files Contain in the subfolders and in the folders in to .txt file.
Can any one say me how do change it .
private void btnSearchNow_Click(object sender, EventArgs e)
{
BLSecurityFinder lSecFinder = new BLSecurityFinderClass();
int iCounter = 0;
lbselected.Items.Clear();
lSecFinder.bScanSubDirectories = chkSubfolders.Checked;
try
{
lSecFinder.FindSecurity(txtSymbol.Text, txtDirectory.Text);
while (lSecFinder.bSecLeft)
{
// Insert(iCounter, lSecFinder.SecName);
lbselected.Items.Add(new SampleData() { Name = lSecFinder.SecName });
lbselected.DisplayMember = "Name";
lSecFinder.FindNextSecurity();
iCounter++;
}
}
catch (System.Runtime.InteropServices.COMException ComEx)
{
//MessageBox.Show (ComEx.Message);
}
finally
{
lSecFinder.DestroySearchDialog();
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
thanks in addvance
var searchPattern = "*.*";
var output = #"c:\results.txt";
var files = Directory.GetFiles(folderBrowserDialog1.SelectedPath,
searchPattern,
chkSubfolders.Checked ? SearchOption.AllDirectories:SearchOption.TopDirectoryOnly);
File.WriteAllLines(output, files);
you can use System.IO class library DirectoryInfo and FileInfo class and the logic goes as follows
1) Create two functions on to process directory and one to process file
2) In which directory read function reads validate if the item is file or directory
3) If the item is directory it recursively calls itself 4) If the item is file it send it to file process method for processing
public void fnProcessDirectory(string strPath)
{
if (File.Exists(strPath))
{
fnProcessFile(strPath);
}
else if (Directory.Exists(strPath))
{
string[] fileEntries = Directory.GetFiles(strPath);
string[] subdirEntries = Directory.GetDirectories(strPath);
foreach (string fileName in fileEntries)
{
fnProcessFile(fileName);
}
foreach (string dirName in subdirEntries)
{
fnProcessDirectory(dirName);
}
}
}
public void fnProcessFile(string strPath)
{
//write the file name in the txt file
}
This will get all the folder and sub-folder filesNames.
you can specify the type of file you looking for or * to get every file.
public void File_To_Text(string filepath)
{
string [] fname;
fname = Directory.GetFiles(filepath, "*.*", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();
File.WriteAllLines("c:\\images.txt", fname, Encoding.UTF8);
}
Here is another version which extends your code directly:
private void btnSearchNow_Click(object sender, EventArgs e)
{
BLSecurityFinder lSecFinder = new BLSecurityFinderClass();
int iCounter = 0;
lbselected.Items.Clear();
lSecFinder.bScanSubDirectories = chkSubfolders.Checked;
using (StreamWriter writer = new StreamWriter(#"C:\results.txt", false))
{
try
{
lSecFinder.FindSecurity(txtSymbol.Text, txtDirectory.Text);
while (lSecFinder.bSecLeft)
{
// Insert(iCounter, lSecFinder.SecName);
lbselected.Items.Add(new SampleData() { Name = lSecFinder.SecName });
lbselected.DisplayMember = "Name";
// assuming SecName is the full filename
writer.WriteLine(lSecFinder.SecName);
lSecFinder.FindNextSecurity();
iCounter++;
}
}
catch (System.Runtime.InteropServices.COMException ComEx)
{
//MessageBox.Show (ComEx.Message);
}
finally
{
lSecFinder.DestroySearchDialog();
}
}
}

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