我单独文件或则单独删夹都没错,但是如果同时文件和文件夹就出错了,为什么啊 。还有谁有更好的方法判断是文件夹还是文件?
代码:
protected bool Deletefile(string strfile)
{
string[] fs = filename.Split(new char[] { ',' }); //获得选中的文件名称
string path = "";
for (int i = 1; i < fs.Length; i++)
{
path = Request.Cookies["Info"].Values["path"].ToString() + "\\" + fs[i];
if (fs[i].LastIndexOf(".") != -1) //判断是文件还是文件夹
{
FileInfo file = new FileInfo(path);
if (!file.Exists) return false;
file.Delete();
}
else
{
DirectoryInfo dir = new DirectoryInfo(path);
if (dir.Exists)
{
dir.Delete();
}
} }
return true;
}
代码:
protected bool Deletefile(string strfile)
{
string[] fs = filename.Split(new char[] { ',' }); //获得选中的文件名称
string path = "";
for (int i = 1; i < fs.Length; i++)
{
path = Request.Cookies["Info"].Values["path"].ToString() + "\\" + fs[i];
if (fs[i].LastIndexOf(".") != -1) //判断是文件还是文件夹
{
FileInfo file = new FileInfo(path);
if (!file.Exists) return false;
file.Delete();
}
else
{
DirectoryInfo dir = new DirectoryInfo(path);
if (dir.Exists)
{
dir.Delete();
}
} }
return true;
}
d.Delete(true)
{
foreach(System.IO.DirectoryInfo d in path.GetDirectories())
{
deletefile(d);
}
foreach(System.IO.FileInfo f in path.GetFiles())
{
f.Delete();
}
}
{
if(File.Exists(path))
File.Delete(path);
else
delDir(new DirectoryInfo(path));
} void delDir(DirectoryInfo dir)
{
foreach (FileInfo f in dir.GetFiles())
f.Delete();
foreach (DirectoryInfo d in dir.GetDirectories())
delDir(d);
dir.Delete();
}
Dim strDirectoryDesPath As String = DirectoryDes.FullName & "\" & DirectorySrc.Name
If Not Directory.Exists(strDirectoryDesPath) Then
Directory.CreateDirectory(strDirectoryDesPath)
End If Dim f, fs() As FileInfo fs = DirectorySrc.GetFiles() For Each f In fs
File.Copy(f.FullName, strDirectoryDesPath & "\" & f.Name, True)
Next Dim DirSrc, Dirs() As DirectoryInfo
Dirs = DirectorySrc.GetDirectories() '递归调用自身
For Each DirSrc In Dirs
Dim DirDes As New DirectoryInfo(strDirectoryDesPath)
CopyDerictory(DirSrc, DirDes)
Next
End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
CopyDerictory(New DirectoryInfo("C:\Documents and Settings\username\Favorites"), New DirectoryInfo("g:\temp"))
End Sub
/// <summary>
/// 判断输入路径为文件还是文件夹
/// </summary>
/// <param name="fnPath">输入的路径</param>
/// <returns>1:文件、2:文件夹、3:不存在</returns>
private int IsFile(string fnPath)
{
if (File.Exists(fnPath))
{
return 1;
}
else
{
if (Directory.Exists(fnPath))
{
return 2;
}
}
return 3;
}2、这段代码“DirectoryInfo dir = new DirectoryInfo(path);
if (dir.Exists)
{
dir.Delete(); ”中
dir.Delete()应该为“dir.Delete(true)”3、for循环中应作出fs[i]是否为空字符的判断。
4、在for循环中,若路径不存在,不应是return,应该是continue。