首先你可以验证,如果你有机会获得该文件,之后,如果该文件存在之间的流创建使用try catch块,看:
public bool HasDirectoryAccess(FileSystemRights fileSystemRights, string directoryPath)
{
DirectorySecurity directorySecurity = Directory.GetAccessControl(directoryPath);
foreach (FileSystemAccessRule rule in directorySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
if ((rule.FileSystemRights & fileSystemRights) != 0)
{
return true;
}
}
return false;
}
所以:
if (this.HasDirectoryAccess(FileSystemRights.Read, path)
{
if (File.Exists(path))
{
try
{
using (Streamwriter ....)
{
// write code
}
}
catch (Exception ex)
{
// throw error if exceptional else report to user or treat it
}
}
else
{
// throw error if exceptional else report to user
}
}
或者你可以使用try catch来验证所有东西,并在try catch内创建流。
如果用户删除'if'和'using'之间的文件,该怎么办? – SLaks 2012-02-29 17:36:46
职位:http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx – cadrell0 2012-02-29 17:40:31