美好的一天!
我正在尝试创建一个C#Forms应用程序,用户在其中选择带有FolderDialog的目录,并在textBox1读取后将路径保存在list.txt文件中。在list.txt中,用户可以添加和删除路径。
代码段:
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格式:
C:/downloads
F:/doc/scan
D:/etc
t仅删除子文件夹和文件很重要,但必须保留根文件夹。到目前为止,我已经完成了对c#的微弱知识,现在我已经被困了很长时间了。 DeleteFilesFromDirectory仅删除textBox1的第一行。
如何使DeleteFilesFromDirectory读取并删除textBox1中的所有行?
检查一下,我测试了它。
//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