Delete all folders inside folder? - c#

Hey guys so I'm working on a small program which sorta speeds up your pc, but I have a problem I get an exception if I try to delete files, I believe cause they are in use. Though it deletes some, but not much. My question is how to delete files in use, and how to delete sub folders inside the folder
//this is my directory:
DirectoryInfo tempPath = new DirectoryInfo(#"C:\Users\" + Environment.UserName + #"\AppData\Local\Temp");
private void button8_Click(object sender, EventArgs e)
{
if (checkBox5.Checked)
{
//loop through these files
foreach (FileInfo file in tempPath.GetFiles())
{
//delete files in content
file.Delete();
}
}
}

You must delete Folder recursivly with set FileAttributes normal.
private static void DeleteAllFolderRecursive(DirectoryInfo yourBaseDir)
{
baseDir.Attributes = FileAttributes.Normal;
foreach (var childDir in baseDir.GetDirectories())
DeleteFolderRecursive(childDir);
foreach (var file in baseDir.GetFiles())
file.IsReadOnly = false;
baseDir.Delete(true);
}
And you call this :
DirectoryInfo tempPath = new DirectoryInfo(#"C:\Users\" + Environment.UserName + #"\AppData\Local\Temp");
DeleteAllFolderRecursive(tempPath);

Related

Skip file renaming conversation if #2 or #3 or #(any number) exist in the file name

Below is my code where I am successfully renaming only the files inside a a folder and also crawls inside every subfolders and renames the entire .png files.
I am trying to add a customization where if the file name already got #1 or #5 or any #(number) then i want the conversation to skip that file and go to next file
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
//folderDlg.ShowDialog();
if (folderDlg.ShowDialog() != DialogResult.OK)
{
return;
}
// Has different framework dependend implementations
// in order to handle unauthorized access to subfolders
RenameAllPngFiles(folderDlg.SelectedPath);
}
private void RenameAllPngFiles(string directoryPath)
{
RenameCurrentPng(directoryPath);
foreach (var item in GetDirectoryInfos(directoryPath))
{
RenameCurrentPng(item.FullName);
}
}
private void RenameCurrentPng(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png"))
{
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
private DirectoryInfo[] GetDirectoryInfos(string directoryPath)
{
DirectoryInfo di = new DirectoryInfo(directoryPath);
DirectoryInfo[] directories = di.GetDirectories("*", System.IO.SearchOption.AllDirectories);
return directories;
}
Just use the String.Contains method to check for #.
private void RenameCurrentPng(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png"))
{
string ShortFileName = System.IO.Path.GetFileNameWithoutExtension(originalFullFileName);
if (!ShortFileName.Contains("#"))
{
// The new file name without path
var newFileName = $"{ShortFileName}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
}

How do I get and display all the file sizes from the file array

I am new to programming, currently trying to get all the file sizes from the file array and display next to them. I found the solution which is FileInfo, but have no idea how it works and couldn't find any solution online. The file array retrieved and display successfully before I added the FileInfo line.
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog()==DialogResult.OK)
{
listBox1.Items.Clear();
string[] files = Directory.GetFiles(FBD.SelectedPath);
string[] dirs = Directory.GetDirectories(FBD.SelectedPath);
foreach (string file in files)
{
long length = new FileInfo(FBD.SelectedPath).Length; //FileNotFoundException
listBox1.Items.Add(Path.GetFileName(file + length));
}
foreach (string dir in dirs)
{
listBox1.Items.Add(Path.GetFileName(dir));
}
}
}
I have a button which can open the folder dialog and user are able to select the directory, and a listbox to display all the file/directory from the selected path. Can I actually get all the files sizes along the path and display next to the files/ directory?
Not with Directory.GetFiles you can't - it returns an array of strings that are filepaths. You'd have to make a new FileInfo from each one and get its length.. It'd be better to call the method of DirectoryInfo that returns you an array of FileInfo to start with:
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog()==DialogResult.OK)
{
listBox1.Items.Clear();
FileInfo[] files = new DirectoryInfo(FBD.SelectedPath).GetFiles();
string[] dirs = Directory.GetDirectories(FBD.SelectedPath);
foreach (FileInfo file in files)
{
listBox1.Items.Add(file.Name + "(" + file.Length + " bytes)");
}
foreach (string dir in dirs)
{
listBox1.Items.Add(Path.GetFileName(dir));
}
}
}
I'm not really sure what you mean by "Can I actually get all the files sizes along the path and display next to the .. directory"
Directories don't have a file size; did you mean that you want the sum total of all the files' sizes inside the directory? For all subdirectories in the hierarchy or the top directory only? Perhaps something like this:
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog()==DialogResult.OK)
{
listBox1.Items.Clear();
FileInfo[] files = new DirectoryInfo(FBD.SelectedPath).GetFiles();
DirectoryInfo[] dirs = new DirectoryInfo(FBD.SelectedPath).GetDirectories();
foreach (FileInfo file in files)
{
listBox1.Items.Add(file.Name + "(" + file.Length + " bytes)");
}
foreach (DirectoryInfo dir in dirs)
{
listBox1.Items.Add(dir.Name + "(" + dir.GetFiles().Sum(f => f.Length) + " bytes)");
}
}
}
For Sum to work you'll have to have imported System.Linq
Incidentally, I present the following as a commentary on why your code didn't work:
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog()==DialogResult.OK)
{
listBox1.Items.Clear();
string[] files = Directory.GetFiles(FBD.SelectedPath);
string[] dirs = Directory.GetDirectories(FBD.SelectedPath);
foreach (string file in files) //ok, so file is the filepath
{
//it doesn't work because you put "FBD.SelectedPath" in instead of "file"
// FBD.SelectedPath is a directory, not a file, hence the FileNotFoundException
//But the real problem is probably a cut n paste error here
long length = new FileInfo(FBD.SelectedPath).Length;
//it would work out but it's a weird way to do it, adding the length on before you strip the filename out
//Path doesnt do anything complex, it just drops all the text before the
//last occurrence of /, but doing Path.GetFilename(file) + length would be better
listBox1.Items.Add(Path.GetFileName(file + length));
}
foreach (string dir in dirs)
{
//need to be careful here: "C:\temp\" is a path of a directory but calling GetFilename on it would return "", not temp
listBox1.Items.Add(Path.GetFileName(dir));
}
}
}
You almost had it right, try the following:
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Clear();
string[] files = Directory.GetFiles(folderBrowser.SelectedPath);
foreach (string file in files)
{
var fileInfo = new FileInfo(file);
listBox1.Items.Add($"{Path.GetFileName(file)} {fileInfo.Length} bytes.");
}
}
}

C# Forms read textBox1 all lines and delete given paths?

Good day!
I'm trying to create a C # Forms app where user chooses directories with FolderDialog and paths are saved in list.txt file after read by textBox1.
In list.txt user can add and delete path.
code snippet:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Lines = System.IO.File.ReadAllLines(fileName);
}
string fileName = Environment.CurrentDirectory + #"/etc/list.txt";
private void LoadTextboxes()
{
string[] loadedLines = System.IO.File.ReadAllLines(Environment.CurrentDirectory + #"/etc/list.txt");
int index = 0;
int n = int.Parse(loadedLines[index]);
string[] lines = new string[n];
Array.Copy(loadedLines, index + 1, lines, 0, n);
textBox1.Lines = lines;
}
private void DeleteFilesFromDirectory(string directoryPath)
{
DirectoryInfo d = new DirectoryInfo(directoryPath);
foreach (FileInfo fi in d.GetFiles())
{
fi.Delete();
}
foreach (DirectoryInfo di in d.GetDirectories())
{
DeleteFilesFromDirectory(di.FullName);
di.Delete();
}
}
private void button1_Del(object sender, EventArgs e)
{
DeleteFilesFromDirectory(textBox1.Text);
}
list.txt format:
C:/downloads
F:/doc/scan
D:/etc
t is important to delete only the sub folders and files but root folders must remain.
So far I have been done with my weak knowledge of c# and and now I'm stuck for a long time.
DeleteFilesFromDirectory only deletes the first line of textBox1.
How to make DeleteFilesFromDirectory read and delete all lines from textBox1?
Check this I tested it.
//put all paths in array reading line by line
string[] paths = System.IO.File.ReadAllLines(#"path-to\list.txt");
//get line by line paths
foreach (string path in paths)
{
if (Directory.Exists(path))
{
//deletes all files and parent
//recursive:true, deletes subfolders and files
Directory.Delete(path, true);
//create parent folder
Directory.CreateDirectory(path);
}
}//end outer for

Getting the song location and play selected treeNode

hi i have been trying for a while with this before i resorted to here
heres in my current code
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
string selectedNodeText = e.Node.Text;
string location = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
mediaPlayer.URL = location + "\\" + selectedNodeText;
}
//
heres how i load the treeView
string music = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
DirectoryInfo directoryInfo = new DirectoryInfo(music);
if (directoryInfo.Exists)
{
treeView1.AfterSelect += treeView1_AfterSelect;
BuildTree(directoryInfo, treeView1.Nodes);
}
}
public void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe)
{
TreeNode curNode = addInMe.Add(directoryInfo.Name);
foreach (FileInfo file in directoryInfo.GetFiles())
{
curNode.Nodes.Add(file.FullName, file.Name);
}
foreach (DirectoryInfo subdir in directoryInfo.GetDirectories())
{
BuildTree(subdir, curNode.Nodes);
}
}
it plays the selected treeNode in mediaplayer but its not playing a song from a sub directory in music any help will make my day
thanks in advance
Your selectedNode only has the song name. When you try to play the sound from a sub directory, you are missing the sub directory from the path and hence it is not playing. You are currently using the Base Music Directory + Song Name.
In the case of a sound file in a sub directory you need to build the path using Base Music Directory + Sub Directory + Song Name
You can get this Sub Directory, either by saving it in your Tree Node Tag or build it from the Tree Heirarchy.
Additionally, use System.IO.Path.Combine. It will save you the trouble of slashes and joining strings to create a valid file path.
In your example you could add the full path to the TreeNode Tag and then use it to play the file later.
public void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe)
{
TreeNode curNode = addInMe.Add(directoryInfo.Name);
foreach (FileInfo file in directoryInfo.GetFiles())
{
TreeNode musicNode = curNode.Nodes.Add(file.FullName, file.Name);
musicNode.Tag = file.FullName;
}
foreach (DirectoryInfo subdir in directoryInfo.GetDirectories())
{
BuildTree(subdir, curNode.Nodes);
}
}
And then to play the file
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
string selectedNodeText = e.Node.Text;
//Ensure that this is not a directory node
if (e.Node.Tag != null) {
string location = e.Node.Tag;
mediaPlayer.URL = location;
}
}

How to delete Files,MainFolder and SubFolders

I am having a problem in deleting Files,MainFolder And SubFolders in a Directory. I want to delete all the Files,MainFolders and Subfolders after the work is finish . I am using this following code.
private void bgAtoZ_DoWork(object sender, DoWorkEventArgs e)
{
string Path1 = (string)(Application.StartupPath + "\\TEMP\\a-z\\test" + "\\" +name);
StreamReader reader1 = File.OpenText(Path1);
string str = reader1.ReadToEnd();
reader1.Close();
reader1.Dispose();
File.Delete(Path1);
}
If anyone Would help me it would be nice for me.
Thanks In Advance
Direcory.Delete(path, true);
See here
I'd go for a:
Directory.Delete(Path1, true)
that will delete folders and files contained.
Directory.Delete(#"c:\test", true); would do it
new System.IO.DirectoryInfo("C:\Temp").Delete(true);
//Or
System.IO.Directory.Delete("C:\Temp", true);
using System.IO;
private void EmptyFolder(DirectoryInfo directoryInfo)
{
foreach (FileInfo file in directoryInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
{
EmptyFolder(subfolder);
}
}
To use the code:
EmptyFolder(new DirectoryInfo(#"C:\yourPath"))
Taken from here.

Categories

Resources