3 回答

TA貢獻1851條經驗 獲得超3個贊
你應該注意到try-catch 永遠不應該成為你代碼邏輯的一部分,這意味著你永遠不應該使用 try-catch 來控制你的分支。這就是為什么您會發(fā)現(xiàn)很難讓異常流過每個 catch 塊的原因。
如果你想抓住第二個塊,你可以這樣寫(但不推薦):
try
{
SPFile destFile = projectid.RootFolder.Files.Add(destUrl, fileBytes, false);
}
catch (System.IO.DirectoryNotFoundException e)
{
try
{
SPFile destFile = projectid.RootFolder.Files.Add(destUrl2, fileBytes, false);
}
catch
{
// Do what you want to do.
}
}
catch
{
}
你最好不要像上面那樣寫。相反,建議像這樣檢測前面存在的文件夾:
try
{
YourMainMethod();
}
catch (Exception ex)
{
// Handle common exceptions that you don't know when you write these codes.
}
void YourMainMethod()
{
var directory = Path.GetDirectoryName(destUrl);
var directory2 = Path.GetDirectoryName(destUrl2);
if (Directory.Exists(directory))
{
SPFile destFile = projectid.RootFolder.Files.Add(destUrl, fileBytes, false);
}
else if (Directory.Exists(directory2))
{
SPFile destFile = projectid.RootFolder.Files.Add(destUrl2, fileBytes, false);
}
else
{
// Handle the expected situations.
}
}

TA貢獻1850條經驗 獲得超11個贊
使用File.Exists查看路徑是否已經存在可能更有意義,然后嘗試寫入文件:
string path = null;
if(!File.Exists(destUrl))
{
path = destUrl;
}
else
{
if(!File.Exists(destUrl2))
{
path = destUrl2;
}
}
if(!string.IsNullOrWhiteSpace(path))
{
try
{
SPFile destFile = projectid.RootFolder.Files.Add(path, fileBytes, false);
}
catch
{
// Something prevented file from being written -> handle this as your workflow dictates
}
}
然后,您希望發(fā)生的唯一例外是寫入文件失敗,您需要按照應用程序的要求進行處理(權限問題的處理方式應與無效的二進制數(shù)據(jù)、損壞的流等不同)。
- 3 回答
- 0 關注
- 174 瀏覽
添加回答
舉報