首先你可以驗證,如果你有機會獲得該文件,之後,如果該文件存在之間的流創建使用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