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);
}
}
}
Related
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);
Can anybody help me write multiple lines to Text file and then search a specific word in that file. I hope the code will use (File.Exists) if any.... thank you in advance
My Code:
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
string lines = textBox1.Text;
StreamWriter file2 = new StreamWriter("D:\\test.txt",true);
file2.WriteLine(lines);
file2.Close();
string text = textBox1.Text;
StreamReader file3 = new StreamReader("D:\\test.txt");
while ((line = file3.ReadLine()) != null)
{
if (line.Contains(text))
{
MessageBox.Show("Name "+text+" is Found!");
textBox2.Text = text;
break;
}
counter++;
}
file3.Close();
}
thank you all .... I lastly found my Answer I modified the code as below:
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
string lines = textBox1.Text;
StreamWriter file2 = new StreamWriter("D:\\test.txt",true);
file2.WriteLine(lines);
file2.Close();
string text = textBox2.Text;
StreamReader file3 = new StreamReader("D:\\test.txt");
while ((line = file3.ReadToEnd()) != null)
{
if (line.Contains(text))
{
MessageBox.Show("Name "+text+" is Found!");
textBox2.Text = text;
break;
}
counter++;
}
file3.Close();
}
How can I limit the number of files to be uploaded using the multi-select openfiledialog in c#?
Here's my code:
private void btn_upload_Click(object sender, EventArgs e)
{
OpenFileDialog op1 = new OpenFileDialog();
op1.Multiselect = true;
op1.ShowDialog();
op1.Filter = "allfiles|*.xls";
textBox1.Text = op1.FileName;
int count = 0;
string[] FName;
foreach (string s in op1.FileNames)
{
FName = s.Split('\\');
File.Copy(s, "C:\\file\\" + FName[FName.Length - 1]);
count++;
}
MessageBox.Show(Convert.ToString(count) + " File(s) copied");
}
It will upload as how much the user wants to. But I want to limit it by 5 files only.
You can't do that directly but you can check the selected files count and display a message to user:
if(op1.FileNames.Length > 5)
{
MessageBox.Show("your message");
return;
}
Or you can take the first five file from selected files:
foreach (string s in op1.FileNames.Take(5))
{
...
}
I just tested and this works:
private void btn_upload_Click(object sender, EventArgs e)
{
OpenFileDialog op1 = new OpenFileDialog();
op1.Multiselect = true;
op1.FileOk += openFileDialog1_FileOk; // Event handler
op1.ShowDialog();
// etc
}
void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
OpenFileDialog dlg = sender as OpenFileDialog;
if (5 < dlg.FileNames.Length)
{
MessageBox.Show("Too Many Files");
e.Cancel = true;
}
}
Is it possible to display a listbox content, with only certain files that have a certain format? like BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff only these files with these extensions that I want to display within the lstFiles listbox.
I have tried,
lstFiles.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff";
But this did not work, is it possible?
EDIT:
I have three joint listboxes to display the system drive, folders and its content
private void lstDrive_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFolders.Items.Clear();
try
{
DriveInfo drive = (DriveInfo)lstDrive.SelectedItem;
foreach (DirectoryInfo dirInfo in drive.RootDirectory.GetDirectories())
lstFolders.Items.Add(dirInfo);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void lstFolders_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFiles.Items.Clear();
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles())
lstFiles.Items.Add(fi);
}
private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(((FileInfo)lstFiles.SelectedItem).FullName);
}
private int lastIndex = 0;
private void lstFiles_KeyUp(object sender, KeyEventArgs e)
{
if (lstFiles.SelectedIndex == lastIndex)
{
if (e.KeyCode == Keys.Up)
{
lstFiles.SelectedIndex = lstFiles.Items.Count - 1;
}
if (e.KeyCode == Keys.Down)
{
lstFiles.SelectedIndex = 0;
}
}
lastIndex = lstFiles.SelectedIndex;
}
}
}
You are population the listbox yourself using a FileInfo object. FileInfo has a property Extension. You can use that one for filtering:
private void lstFolders_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFiles.Items.Clear();
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles())
switch(fi.Extension.ToUpperInvariant())
{
case ".BMP":
case ".JPG":
...
lstFiles.Items.Add(fi);
break;
}
}
Ok, I personaly have no idea nor have ever heard of using "filter" on a list box. Why don't you just add the items you want when you have the list?
lstFiles.Items.Clear();
List<string> allowedExtensions = new List<string>() {".jpg", ".png", ".gif"};
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles().Where((x)=>allowedExtensions.Contains(x)))
{
lstFiles.Items.Add(fi);
}
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);
}