Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Wednesday, June 26, 2013 4:15 PM
how can I check if file exists ,but by reading the file names from a list box
All replies (3)
Wednesday, June 26, 2013 4:28 PM ✅Answered
You can use System.IO.File.Exists(filepath) method to return a bool if the file exists.
You can use the list box's .Items collection to get each list box entry.
foreach(string path in myListBox.Items) {
if(!System.IO.File.Exists(path)) {
MessageBox.Show("The file " + path + " does not exist");
}
}
Wednesday, June 26, 2013 4:29 PM ✅Answered
Try code below
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;namespace WindowsFormsApplication1{ public partial class Form1 : Form { public Form1() { InitializeComponent(); List<string> files = Directory.GetFiles(@"c:\temp").ToList(); //fill listbox with file names listBox1.Items.AddRange(files.ToArray()); } private void button1_Click(object sender, EventArgs e) { foreach (string filename in listBox1.Items) { if (File.Exists(filename)) { Console.WriteLine("File Exists : {0}", filename); } else { Console.WriteLine("File Does not Exists : {0}", filename); } } Console.ReadLine(); } }}
jdweng
Wednesday, June 26, 2013 4:45 PM ✅Answered
Georges : Hope this helps
bool fileExists = false;
//change yourPath and fileName accordingly
string yourPath = @"c:\temp\";
string fileName = listBox1.SelectedItem.ToString();
if (Directory.GetFiles(yourPath, fileName, SearchOption.AllDirectories).Count() > 0) fileExists = true;
//your code if file Exists = true