Reloading comboBox using resetText() - c#

private void ReloadForm()
{
comboBox4.ResetText();
}
private void button2_Click(object sender, EventArgs e)
{
string layers = textBox1.Text;
FileStream fs = new FileStream("xml/" + layers + ".xml", FileMode.Create);
XmlWriter w = XmlWriter.Create(fs);
w.WriteStartDocument();
w.WriteStartElement("layers");
// Write a product.
w.WriteStartElement("layer");
w.WriteAttributeString("id", "1");
w.WriteElementString("layerName", layers);
w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();
ReloadForm();
}
public Form3()
{
InitializeComponent();
// Put XML name files in comboBox4
string[] filePaths = Directory.GetFiles(#"xml\", "*");
foreach (string file in filePaths)
{
string mypath = file;
string[] directories = mypath.Split(Path.DirectorySeparatorChar);
foreach (string dir in directories){
comboBox4.Items.Add(dir);
}
}
}
The code above create XML files on click and I got seperate code that display the name of each XML file.
I've tried to use void ReloadForm() to refresh comboBox4 text, but It failed..
Any ideas how to fix that?

change your Form3 constructor to this
public Form3()
{
InitializeComponent();
ReloadComboBox4();
}
and rename your ReloadForm() to ReloadComboBox4 and change it to this
private void ReloadComboBox4()
{
comboBox4.Items.Clear()
string[] filePaths = Directory.GetFiles(#"xml\", "*");
foreach (string file in filePaths)
{
string mypath = file;
string[] directories = mypath.Split(Path.DirectorySeparatorChar);
foreach (string dir in directories)
{
comboBox4.Items.Add(dir);
}
}
}

Related

Overwrite file only works once

I have a simple program that copies files and directories from one place to another. I have it set-up that if there are any exceptions (such as if access to the path is denied) it will create a log file with the error.
I have a button that when pressed, performs the copy action. Everything works fine the first time I press the button and the log file is either created or overwritten with the appropriate error messages.
However, if I press the button a second time, the text file is not overwritten and instead the error messages append. If I close out of my program and run it again, the file is overwritten on the first button press. Any thoughts would be greatly appreciated.
target is a string filepath which I'm getting from a FolderBrowserDialog and taking the selected path and setting it to a textbox. loglist is just a simple List<string> I'm using to store the error messages from any exceptions that occur during the copy process.
public partial class Form1 : Form
{
static List<string> logList = new List<string>();
public Form1()
{
InitializeComponent();
}
private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (source.FullName.ToLower() == target.FullName.ToLower())
return;
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
foreach (FileInfo fi in source.GetFiles())
{
try
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
catch (Exception ex)
{
logList.Add(ex.Message);
}
}
foreach (DirectoryInfo diSourceSub in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSub.Name);
CopyAll(diSourceSub, nextTargetSubDir);
}
}
private void directoryPickerBtn1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
DialogResult folderResult = folderDialog.ShowDialog();
if (folderResult == DialogResult.OK)
{
directoryTextbox1.Text = folderDialog.SelectedPath;
}
}
private void directoryPickerBtn2_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
DialogResult folderResult = folderDialog.ShowDialog();
if (folderResult == DialogResult.OK)
{
directoryTextbox2.Text = folderDialog.SelectedPath;
}
}
private void copyBtn_Click(object sender, EventArgs e)
{
string source = (directoryTextbox1.Text);
string target = (directoryTextbox2.Text);
DirectoryInfo dirSource = new DirectoryInfo(source);
DirectoryInfo dirTarget = new DirectoryInfo(target);
try
{
CopyAll(dirSource, dirTarget);
if (logList.Count > 0)
{
using (StreamWriter sw = new StreamWriter(target + #"\log.txt", false))
{
foreach (string error in logList)
{
sw.WriteLine(error);
}
}
}
DialogResult result = MessageBox.Show("Copy Succeeded", "Success");
if (result == DialogResult.OK)
{
string myPath = dirTarget.ToString();
System.Diagnostics.Process prc = new System.Diagnostics.Process();
prc.StartInfo.FileName = myPath;
prc.Start();
}
}
catch (Exception)
{
MessageBox.Show("Copy Failed", "Failed");
}
}
}
}
As #Reza Aghaei pointed out in comments, the problem is that you do not clear the logList.
The file gets created anew every time, but each time you click the Copy button, the loglist still contains the results of the previous copy action.
So you need to clear the list when starting a new copy:
private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
logList.Clear();
// ...
From your code it seems that you never clear the logList, this means that it appears the file is being appending because the logList still contains all of the old entries.
You'll need to clear the list between copies if you only want relevant entries to that copy, either before you start copying or after you finish writing the file.
This would be better as a separate method
try
{
CopyAll(dirSource, dirTarget);
SaveLog(target + #"\log.txt");
ClearLog();
//...
}
private void SaveLog(string filename)
{
if (logList.Count > 0)
{
FileStream fs = File.Open(target + #"\log.txt", FileMode.Create);
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (string error in logList)
{
sw.WriteLine(error);
}
}
}
}

Searching inside a subfolder in asp.net

How can I search a file thats inside a subfolder
Here's my code it currently searches the parent folder only it won't search inside the sub folder:
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] files = Directory.GetFiles(Server.MapPath("~/files"));
foreach (string item in files)
{
string fileName = Path.GetFileName(item);
if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
{
ListBox1.Items.Add(fileName);
}
}
}
You can do it like this
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] files = Directory.GetFiles(Server.MapPath("~/files"), "*.*", SearchOption.AllDirectories);
foreach (string item in files)
{
string fileName = Path.GetFileName(item);
if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
{
ListBox1.Items.Add(fileName);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
DirectoryInfo di =
new DirectoryInfo(Server.MapPath("~/files"));
FileInfo[] files =
di.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo item in files)
{
string fileName = item.Name;
if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
{
ListBox1.Items.Add(fileName);
}
}
}

Removing Info Before Filename.exe

This lists all files in all directory's from the directory i choose with folderBrowserDialog1, but when it loads them into the listBox it comes up with the item in the listBox like this
C:\users\username\desktop\filename.exe
C:\users\username\desktop\filename.exe
C:\users\username\desktop\filename.exe
and so on.. is there any way to remove C:\users\username\desktop\ and just keep filename.exe
Here's my code it may help.
private void DirSearch(string dir)
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (var file in files)
{
ListBox2.Items.Add(file);
}
}
Use Path.GetFileName method:
ListBox2.Items.Add(Path.GetFileName(file));
From your comment to #Dennis, this should work.
private void DirSearch(string dir)
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (var file in files)
{
ListBox2.Items.Add(file.Replace(dir, string.empty);
}
}
try recursive method
private void Form1_Load(object sender, EventArgs e)
{
DirSearch(folderBrowserDialog1.SelectedPath);
}
private void DirSearch(string dir)
{
try
{
string userpath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
folderBrowserDialog1.ShowDialog();
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
if (!dir.Equals(userpath))
{
foreach (var file in files)
{
listBox1.Items.Add(System.IO.Path.GetFileName(file));
}
IEnumerable<string> dirs = Directory.EnumerateDirectories(dir);
foreach (string dsdir in dirs)
{
DirSearch(dsdir);
}
}
}
catch (Exception ex)
{
}
}

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

Trouble getting my button to call my class

I have a Windows Form application. What this application does, is let the user browse to a drive/folder they wish to have files renamed for. This app renames files that have "invalid" characters (that are defined in a RegEx pattern).
What i want to happen here is, after the user decides which drive/folder to use, a datagridview pops up showing the user files in the drive/folder that are going to be renamed. The user then clicks a button to actually rename the files. I'm having trouble though getting the code for my button in DriveRecursion_Results.cs set up. Can anybody help me? Code plz -- i'm extremely new to this and need syntax to look at to understand.
Form1 code:
namespace FileMigration2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderSelect("Please select:");
}
public string FolderSelect(string txtPrompt)
{
//Value to be returned
string result = string.Empty;
//Now, we want to use the path information to population our folder selection initial location
string initialPathDir = (#"C:\");
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(initialPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
{
retPath = "";
}
DriveRecursion_Results dw = new DriveRecursion_Results();
dw.Show();
dw.DriveRecursion(retPath);
result = retPath;
}
return result;
}
}
}
DriveRecursion_Results.cs code: [the button is in here that i need help with!]
namespace FileMigration2
{
public partial class DriveRecursion_Results : Form
{
public DriveRecursion_Results()
{
InitializeComponent();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DriveRecursion(string retPath)
{
//recurse through files. Let user press 'ok' to move onto next step
// string[] files = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
//string replacement = "";
Regex regEx = new Regex(pattern);
string[] fileDrive = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
List<string> filePath = new List<string>();
dataGridView1.Rows.Clear();
try
{
foreach (string fileNames in fileDrive)
{
if (regEx.IsMatch(fileNames))
{
string fileNameOnly = Path.GetFileName(fileNames);
string pathOnly = Path.GetDirectoryName(fileNames);
DataGridViewRow dgr = new DataGridViewRow();
filePath.Add(fileNames);
dgr.CreateCells(dataGridView1);
dgr.Cells[0].Value = pathOnly;
dgr.Cells[1].Value = fileNameOnly;
dataGridView1.Rows.Add(dgr);
filePath.Add(fileNames);
}
else
{
DataGridViewRow dgr2 = new DataGridViewRow();
dgr2.Cells[0].Value = "No Files To Clean Up";
dgr2.Cells[1].Value = "";
}
}
}
catch (Exception e)
{
StreamWriter sw = new StreamWriter(retPath + "ErrorLog.txt");
sw.Write(e);
}
}
private void button1_Click(object sender, EventArgs e)
{
//What do i type in here to call my FileCleanUp method???
}
}
SanitizeFileNames.cs code:
namespace FileMigration2
{
public class SanitizeFileNames
{
public static void FileCleanup(List<string>filePath)
{
string regPattern = "*[\\~#%&*{}/<>?|\"-]+*";
string replacement = "";
Regex regExPattern = new Regex(regPattern);
foreach (string files2 in filePath)
{
try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
//write to streamwriter
System.IO.File.Move(files2, sanitized);
}
catch (Exception ex)
{
//write to streamwriter
}
}
}
}
}
}
Any help is appreciated!
Thanks :)
Put
public partial class DriveRecursion_Results : Form {
List<string> filePath;
and in driveRecursion method, just use
filePath = new List<string>();
and in the action button method, why don't you do
if(filePath != null)
SanitizeFileNames.FileCleanup(filePath);
You call filePath.Add twice ?
Your 'else' is in the wrong place too.
What is dgr2?

Categories