如何删除c#中的特定文件夹中的文件夹及其文件?
当我尝试运行此代码时:
try{
var dir = new DirectoryInfo(@"uploads//"+civil_case.Text);
dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
dir.Delete(true);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
它还会删除uploads文件夹。我只想删除uploads文件夹中的一个文件夹。
实施例
Uploads >
1stfolder >
> content 1.pdf
> content 2.png
2ndfolder >
> content 1.pdf
> content 2.png
我想删除1stfolder
,但事实证明它也删除了Uploads
文件夹。
答案 0 :(得分:0)
请尝试以下代码:
try {
string[] myFilePaths = Directory.GetFiles(@"uploads//" +civil_case.Text);
foreach (string file_path in myFilePaths)
File.Delete(file_path);
}
catch {
}
答案 1 :(得分:0)
我会这样做:
try
{
var dir = new DirectoryInfo(@"uploads//"+civil_case.Text);
dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
//delete
System.IO.Directory.Delete(@"uploads//"+civil_case.Text, true);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
答案 2 :(得分:0)
我认为你需要改为:
try{
var dir = new DirectoryInfo(@"uploads\") ; //change the // to \
foreach (DirectoryInfo subDir in dir)
{
If(subDir.FullName.Contains(civil_case.Text))
{
subDir.Attributes = subDir.Attributes & ~FileAttributes.ReadOnly;
subDir.Delete(true);
}
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}