Directory search is Not working after using getfiles - c#

I am using Windows form on which I am using a textbox,folderbrowserdialog and listbox control and two button controls.The task is to retrieve specific file type say .txt from the folder in the textbox1. After getting specific file type from textbox1 I want to display it on listbox1.So I used directory.getfile option but it is showing me error of An unhandled exception of type 'System.IO.DirectoryNotFoundException' .Can any one tell me what is wrong on my code.
namespace WinDataStore
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button2_Click(object sender, EventArgs e)
{
var t = this.Controls["textBox1"] as TextBox;
string[] extensions = { ".txt", ".aspx", ".css", ".cs" };
string[] dizin = Directory.GetFiles("t", "*.*")
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
string[] p = dizin;
listBox1.Items.Add(p);
}
}
}

You must pass path of the folder in first parameter:
Directory.GetFiles(t.Text, "*.*")
instead of just passing "t".
Even you don't need to refer to t while you have textBox1 in the same scope, you can directly use:
Directory.GetFiles(textBox1.Text, "*.*")
Now add array to listbox1:
listBox1.Items.AddRange(dizin);

You can change you code like
Check the value of text is not empty.
you can use addrange() method to add value to listbox(before it was adding array object to list box)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button2_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(textBox1.Text))
{
//notification to user
return;
}
//var t = this.Controls["textBox1"] as TextBox;
string[] extensions = { ".txt", ".aspx", ".css", ".cs" };
string[] dizin = Directory.GetFiles(textBox1.Text, "*.*")
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
listBox1.Items.AddRange(dizin);
//string[] p = dizin;
//listBox1.Items.Add(p);
}
}

Change your code in this way:
string[] dizin = Directory.GetFiles(t.Text, "*.*")
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
Becuase you put "t" that is an error, because t is not a string but a variable containing the folder, as I understood looking your code.

The way your are trying to read the path from textbox is not correct. Also do below changes to your code. Also I think there is an issue in the way you're adding items to the listBox. I haven't tested this code. Please try and let me know if you have any issues.
private void button2_Click(object sender, EventArgs e)
{
string path = textBox1.Text;
string[] extensions = { ".txt", ".aspx", ".css", ".cs" };
string[] allFiles = Directory.GetFiles(path);
var validFiles = (from file in allFiles from extension in extensions where file.ToLower().Contains(extension) select file).ToList();
foreach (var validFile in validFiles)
{
listBox1.Items.Add(new ListBoxItem(validFile, validFile));
}
}

Related

How to manipulate or edit a txt file from textbox and save the modification to the main file or new file

I've managed to open a txt file to a ComboBox where it shown only the second element"100", and if I select one of the items in ComboBox will show me the the first element witch is "firstName", the problem is I want to modify the first element from the textbox and save it to the main file or new file on the way that I replace the old element with new one from the textbox and save the file as it was at the beginning
TXT FILE
firstName;;;100;;;0;
firstName;;;100;;;1;
firstName;;;100;;;2;
firstName;;;100;;;3;
firstName;;;0100;;;4;
firstName;;;0100;;;5;
firstName;;;0100;;;6;
firstName;;;0100;;;7;
lastName;;;0100;;;0;
lastName;;;0100;;;1;
lastName;;;0100;;;2;
lastName;;;0100;;;3;
lastName;;;0100;;;4;
lastName;;;0100;;;5;
lastName;;;0100;;;6;
lastName;;;0100;;;7;
i want to change the first elements from the textbox and replace it with user input and save the file as in it were,
example:
//output
john;;;100;;;0;
Patrick;;;100;;;1;
firstName;;;100;;;2;
namespace WindowsFormsApp8
{
public partial class Form1 : Form
{
public string[] lines;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "txt file (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//string[] lines = File.ReadAllLines(openFileDialog.FileName);
lines = File.ReadAllLines(openFileDialog.FileName);
List<string> result = new List<string>();
string[] par = new string[1];
par[0] = ";;;";
for (int i = 0; i < lines.Length; i++)
{
string[] row = lines[i].Split(par, StringSplitOptions.None);
if (row.Length > 2)
{
if (!result.Contains(row[1]))
result.Add(row[1]);
}
}
foreach (string line in result)
{
comboBox1.Items.Add(line);
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var d = lines;
var t = d.Where(g => g.Contains(comboBox1.Text));
string allItems = "";
foreach (string item in t)
{
string[] r = item.Split(new string[] { ";;;" }, StringSplitOptions.None);
allItems += r[0] + Environment.NewLine;
}
textBox1.Text = allItems;
}
}
}
I've read your code carefully and my understanding may not be perfect but it should be close enough that I can help. One way to achieve your objectives is with data binding and I'll demonstrate this step by step.
"open a txt file to a combobox"
In your main form, you'll move the OpenFileDialog so that it is now a member variable:
private OpenFileDialog openFileDialog = new OpenFileDialog
{
InitialDirectory = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Files"),
FileName = "Data.txt",
Filter = "txt file (*.txt)|*.txt|All files (*.*)|*.*",
FilterIndex = 2,
RestoreDirectory = true,
};
In the main form CTor
Handle event buttonLoad.Click to display the dialog
Handle event openFileDialog.FileOk to read the file.
The DataSource of comboBox will be set to the list of lines read from the file.
Initialize
public MainForm()
{
InitializeComponent();
buttonLoad.Click += onClickLoad;
openFileDialog.FileOk += onFileOK;
comboBox.DataSource = lines;
.
.
.
Disposed += (sender, e) => openFileDialog.Dispose();
}
BindingList<Line> lines = new BindingList<Line>();
private void onClickLoad(object? sender, EventArgs e) =>
openFileDialog.ShowDialog();
In a minute, we'll look at those three things step by step. But first...
Serialize and Deserialize
You have a lot of loose code doing string splits to decode your serializer format. Try consolidating this in a class that is also suitable to be used in a BindingList<Line>. This will be the data source of your combo box. Also consider using a standard serialization format like JSON instead!
class Line : INotifyPropertyChanged
{
// Make a Line from serialized like firstName;;;100;;;0;
public Line(string serialized)
{
// Convert to a stored array
_deserialized = serialized.Split(new string[] { ";;;" }, StringSplitOptions.None);
}
// Convert back to the format used in your file.
public string Serialized => string.Join(";;;", _deserialized);
private string[] _deserialized { get; } // Backing store.
// Convert a list of Lines to a collection of strings (e.g. for Save).
public static IEnumerable<string> ToAllLines(IEnumerable<Line> lines) =>
lines.Select(_ => _.Serialized);
// Determine how a Line will be displayed in the combo box (e.g. "0100").
public override string ToString() => _deserialized[1].ToString();
// Use array syntax to access elements of the split array.
public string this[int index]
{
get => _deserialized[index];
set
{
if(!Equals(_deserialized[index],value))
{
// Send event when any array value changes.
_deserialized[index] = value;
OnPropertyChanged($"{index}");
}
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Load
Once the data file is selected, the raw text file will be shown and the combo box will be populated.
private void onFileOK(object? sender, CancelEventArgs e)
{
lines.Clear();
foreach (var serialized in File.ReadAllLines(openFileDialog.FileName))
{
lines.Add(new Line(serialized));
}
textBoxMultiline.Lines = lines.Select(_=>_.Serialized).ToArray();
comboBox.SelectedIndex = -1;
}
Replacement
Going back to the main form CTor there are three more events we care about:
public MainForm()
{
.
.
.
comboBox.SelectedIndexChanged += onComboBoxSelectedIndexChanged;
textBoxEditor.TextChanged += onEditorTextChanged;
lines.ListChanged += onListChanged;
.
.
.
}
When a new item is selected in the combo box, put it in the text editor.
private void onComboBoxSelectedIndexChanged(object sender, EventArgs e)
{
var item = (Line)comboBox.SelectedItem;
if (item != null)
{
textBoxEditor.Text = item[0];
}
}
When the textEditor text changes, modify the item.
private void onEditorTextChanged(object? sender, EventArgs e)
{
var item = (Line)comboBox.SelectedItem;
if (item != null)
{
item[0] = textBoxEditor.Text;
}
}
When the item changes, update the file display in the big textbox.
private void onListChanged(object? sender, ListChangedEventArgs e)
{
switch (e.ListChangedType)
{
case ListChangedType.ItemChanged:
textBoxMultiline.Lines = lines.Select(_=>_.Serialized).ToArray();
break;
}
}
Save
SaveFileDialog saveFileDialog = new SaveFileDialog
{
InitialDirectory = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Files"),
FileName = "Data.txt",
Filter = "txt file (*.txt)|*.txt|All files (*.*)|*.*",
FilterIndex = 2,
RestoreDirectory = true,
};
private void onClickSave(object? sender, EventArgs e) =>
saveFileDialog.ShowDialog(this);
private void onSaveFileOK(object? sender, CancelEventArgs e)
{
File.WriteAllLines(saveFileDialog.FileName, Line.ToAllLines(lines));
}
I hope this is "close enough" to what you have described that if will give you some ideas to experiment with.

I have a query about checked list boxes in c#

I have set up a program that so far can browse for the location of a file that possesses data in a text file holding the locations of other files which then shows me if they exist, are missing or are a duplicate inside listboxes. The next step is to enable the user to select files in the checked list boxes and being given the option to either move or copy. I have already made buttons which allow this but I want to be able to use them for the checked boxes I the list boxes.(p.s) please ignore any comments I have made in the code they are just previous attempts of doing other things in the code.
My code so far:
namespace File_existence
{
public partial class fileForm : Form
{
private string _filelistlocation;
public fileForm()
{
InitializeComponent();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void fileForm_Load(object sender, System.EventArgs e)
{
_filelistlocation = textBox1.Text;
}
private void button1_Click(object sender, System.EventArgs e)
{
//GetDuplicates();
checkedListBox1.Items.Clear();
listBox2.Items.Clear();
ReadFromList();
}
private void GetDuplicates()
{
DirectoryInfo directoryToCheck = new DirectoryInfo(#"C:\\temp");
FileInfo[] files = directoryToCheck.GetFiles("*.*", SearchOption.AllDirectories);
var duplicates = files.GroupBy(x => x.Name)
.Where(group => group.Count() > 1)
.Select(group => group.Key);
if (duplicates.Count() > 0)
{
MessageBox.Show("The file exists");
FileStream s2 = new FileStream(_filelistlocation, FileMode.Open, FileAccess.Read, FileShare.Read);
// open _filelistlocation
// foreach line in _filelistlocation
// concatenate pat hand filename
//
}
}
public void ReadFromList()
{
int lineCounter = 0;
int badlineCounter = 0;
using (StreamReader sr = new StreamReader(_filelistlocation))
{
String line;
while ((line = sr.ReadLine()) != null)
{
string[] values = line.Split('\t');
if (values.Length == 2)
{
string fullpath = string.Concat(values[1], "\\", values[0]);
if (File.Exists(fullpath))
checkedListBox1.Items.Add(fullpath);
else
listBox2.Items.Add(fullpath);
++lineCounter;
}
else
++badlineCounter;
//Console.WriteLine(line);
}
}
}
//StreamReader files= new StreamReader(File)();
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, System.EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
try
{
string fileName = "filetest1.txt";
string sourcePath = #"C:\Temp\Trade files\removed";
string targetPath = #"C:\Temp\Trade files\queued";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath,fileName);
System.IO.File.Copy(sourceFile, destFile, true);
}
catch (IOException exc)
{
MessageBox.Show(exc.Message);
}
}
private void button3_Click(object sender, System.EventArgs e)
{
try
{
string sourceFile = #"C:\Temp\Trade Files\queued\filetest1.txt";
string destinationFile = #"C:\Temp\Trade Files\processed\filetest1.txt";
System.IO.File.Move(sourceFile, destinationFile);
}
catch(IOException ex){
MessageBox.Show(ex.Message);//"File not found"
}
}
private void button4_Click(object sender, System.EventArgs e)
{
OpenFileDialog fileBrowserDlg = new OpenFileDialog();
//folderBrowserDlg.ShowNewFolderButton = true;
//folderBrowserDlg.SelectedPath = _filelistlocation;
fileBrowserDlg.FileName = textBox1.Text;
DialogResult dlgResult = fileBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = fileBrowserDlg.FileName;
File_existence.Properties.Settings.Default.Save();
// Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button5_Click(object sender, System.EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
checkedListBox1.Items.Add(file);
}
}
else
{
checkedListBox1.Items.Add(String.Format("No file found: {0}", textBox1.Text));
}
}
}
}
}
The task I need to do is that the files that appear in the checked list box need to usually be moved or copied to another directory. That is fine as I can already do that with what I have coded, but what it does is it will move or copy all of the files in the checked list box. What I want to do is enable the user to only be able to select which files they what to move or copy through checking the checked list box so that only those files will be moved or copied.
EDIT: Could it be checkedListBox.checked items?

how to find that whether the file exist or not using c#

private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FldrBrowseDlg = new FolderBrowserDialog();
FldrBrowseDlg.ShowNewFolderButton = true;
DialogResult DigRslt = FldrBrowseDlg.ShowDialog();
if (DigRslt.Equals(DialogResult.OK))
{
textBox1.Text = FldrBrowseDlg.SelectedPath;
Environment.SpecialFolder rootfolder = FldrBrowseDlg.RootFolder;
}
}
private void button2_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(textBox1.Text);
FileInfo[] files = dir.GetFiles("*doc.zip", SearchOption.AllDirectories);
foreach (FileInfo fl in files)
{
string s1 = fl.ToString();
string name = s1.Substring(0, 28);
string kyrname = name + ".txt";
if (File.Exists(textBox1.Text+"*/"+kyrname))
{
label1.Text = "have kyrplus";
}
else
{
listBox1.Items.Add(name);
}
I want to search the file but it is not taking the the path that I am giving in File.Exixts() function what to do?
Thats probably because your path is not correct.
File.Exists(textBox1.Text+"*/"+kyrname)
You need to check what is the value in your textBox1.Text and then you can concatenate the value with "*/" and .txt. It doesnt look to me as a valid path.
EDIT:
You can try like this if you are looking for a file in all the subdirectory
var file = Directory.GetFiles(textBox1.Text, kyrname, SearchOption.AllDirectories)
.FirstOrDefault();
if (file == null)
{
// File does not exist
}

compress Data from listbox using ZipFile

I am creating button click event, on clicking it will select data of textbox1 and comboBox1. Further it will search for specific file type from the folder name I provide into textbox1. Currently I am using listbox1 as container for storing value from combobox and textbox. Now I want to Zip the file I got from listbox1. I am using ZipFile to compress it.Now I am stuck in how to call all data from listbox1 for compressing.
namespace WinDataStore
{
public partial class Form1 : Form
{
ComboBox comboBox;
public Form1()
{
InitializeComponent();
var daysOfWeek =
new[] { "RED", "GREEN", "BLUE"
};
comboBox = new ComboBox
{
DataSource = daysOfWeek,
Location = new System.Drawing.Point(180, 140),
Name = "comboBox",
Size = new System.Drawing.Size(166, 21),
DropDownStyle = ComboBoxStyle.DropDownList
};
this.Controls.Add(comboBox);
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
//notification to user
return;
}
string[] extensions = { ".xml",".ddg" };
string[] dizin = Directory.GetFiles(textBox1.Text, "*.*",SearchOption.AllDirectories)
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
listBox1.Items.AddRange(dizin);
var comboBox = this.Controls["comboBox"] as ComboBox;
string s = (string)comboBox.SelectedItem;
listBox1.Items.Add(s);
}
}
}

Combobox value is not selected by ZipFile compression

I am Creating Windows Application.I am using FolderBrowserDialog textBox1 ComboBox and button. In my button click I want to select a combo box value and store in a zip file. But it is not accepting combo box value and showing me error. Any idea how to resolve?
namespace WinDataStore
{
public partial class Form1 : Form
{
ComboBox comboBox;
public Form1()
{
InitializeComponent();
var daysOfWeek = new[] { "RED", "GREEN", "BLUE"};
// Initialize combo box
comboBox = new ComboBox
{
DataSource = daysOfWeek,
Location = new System.Drawing.Point(180, 140),
Name = "comboBox",
Size = new System.Drawing.Size(166, 21),
DropDownStyle = ComboBoxStyle.DropDownList
};
// Add the combo box to the form.
this.Controls.Add(comboBox);
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
var comboBox = this.Controls["comboBox"] as ComboBox;
string s = (string)comboBox.SelectedItem;
using (ZipFile zip = new ZipFile())
{
zip.AddFile("s", "files");
zip.Save("z.zip");
}
}
}
}
Based on your comment above:
System.IO.FileNotFoundException
The .Add() method that you're using expects a file name:
zip.AddFile("s", "files");
Do you really have a file that's just named "s" in the current working directory? The runtime is telling you that you don't. And I'm inclined to believe it. You can't add a file which doesn't exist.
You do have a string variable called s:
string s = (string)comboBox.SelectedItem;
Maybe you meant to use that?:
zip.AddFile(s, "files");

Categories

Resources