Removing Info Before Filename.exe - c#

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

Related

How to delete files from Prefetch or such folders, which requires Administrative Permissions, programmatically via C#

I am building a Windows Form application on C# which would list all files present in Prefetch, Temp and %temp% directory of windows installation and finally would delete them. But I am stuck as at the point where my app is not able to handle below exception. Please help me suggesting the best solution to achieve my goal.
"System.UnauthorizedAccessException: 'Access to the path 'C:\Windows\Prefetch' is denied.'"
My code for windows form app is below
using System;
using System.Windows.Forms;
using System.IO;
namespace ZAP_CLEANER
{
public partial class UC_FullScan : UserControl
{
public UC_FullScan()
{
InitializeComponent();
}
private void ibtn_StartScan_Click(object sender, EventArgs e)
{
string rootPath = #"C:\Windows\Prefetch";
string[] dirs = Directory.GetDirectories(rootPath);
var files = Directory.GetFiles(rootPath);
foreach (string dir in dirs)
{
File.SetAttributes(dir, FileAttributes.Normal);
textBox1.Text += dir;
}
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
textBox1.Text += file;
}
}
public void DeleteDirectory(string targetDir)
{
File.SetAttributes(targetDir, FileAttributes.Normal);
string[] files = Directory.GetFiles(targetDir);
string[] dirs = Directory.GetDirectories(targetDir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(targetDir, false);
}
private void ibtn_Clean_Click(object sender, EventArgs e)
{
string rootPath = #"C:\Windows\Prefetch";
DeleteDirectory(rootPath);
}
}
}

Files without extensions in listbox

1.) How I can remove file extension (".txt")?
2.) Why when I click somewhere to listbox window so all items are replicated???
private void listBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Folder");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
listBox1.Items.Add(file.Name);
}
}
listBox.Items.Clear(); // to clear current listbox items
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
listBox1.Items.Add(Path.GetFileNameWithoutExtension(file.Name));
}

Reloading comboBox using resetText()

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

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

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

Categories