How to delete Files,MainFolder and SubFolders - c#

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.

Related

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

Delete all folders inside folder?

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

How do I get detailed file information if I only have the file name?

I have information about the output file name only.
How do I get the output size and modification date?
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowDialog();
textBox1.Text = fbd.SelectedPath;
DirectoryInfo di = new DirectoryInfo(fbd.SelectedPath);
FileInfo[] files = di.GetFiles();
DirectoryInfo[] directorys = di.GetDirectories();
foreach (FileInfo fil in files)
{
listView2.Items.Add(fil.Name);
}
foreach (DirectoryInfo dir in directorys)
{
listView1.Items.Add(dir.Name);
}
}
All those attributes are on the FileInfo class:
foreach (FileInfo fil in files)
{
listView2.Items.Add(
new ListViewItem(
new string[] {
fil.Name,
fil.LastWriteTime.ToString(),
fil.Length.ToString()
}
)
);
}
File.GetLastWriteTime will get you the last time the file was modified and FileInfo.Length will get you the length of the file if thats what you're looking for.

how do I copy a folder to a USB? C#

I'm working on a project that will automatically update my USB with some files from my computer.
The program works on start up and monitors for any USB or CD that is plugged into the computer. My program is to then copy some folders and its files to the USB. I am having trouble copying the folders into the USB and would appreciate some help, thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// this section starts the timer so it can moniter when a USB or CD is inserted into
// the computer.
//==================================================================================
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Start();
WindowState = FormWindowState.Minimized;
//===================================================================================
}
private void timer1_Tick(object sender, EventArgs e)
{
// this section checks to see if there is a drive type of USB and CDs.
foreach(DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Removable)
{
// this part is supposed to copy a folder from the PC and paste it to the USB
//==============================================================================
//==============================================================================
}
if (drive.DriveType == DriveType.CDRom)
{
// same thing but for CDs.
//==============================================================================
//==============================================================================
}
}
}
// this section opens a folderbrowserdialog that the users can use to access their folders
//and put them into a listbox so when a USB or CD is inserted it will copy those files into
// the storage devices.
//==============================================================================
private void button1_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Add(folderBrowserDialog1.SelectedPath);
//==============================================================================
}
}
}
}
Here is how it can be done:
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
Use File.Copy and use the USB drive letter for the destination. For example:
string sourceDir = #"c:\current";
string backupDir = #"f:\archives\2008";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy picture files.
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Delete source files that were copied.
foreach (string f in txtList)
{
File.Delete(f);
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
please refer to MSDN:
http://msdn.microsoft.com/en-us/library/bb762914.aspx

Categories

Resources