如果有可能,你應該嘗試av oid拋出異常只是爲了向用戶顯示一條消息或者可以輕鬆測試的條件。這主要是性能考慮因素,因爲拋出異常很昂貴。此外,除非您知道該文件相對較小,否則可能會將性能加載到內存中。
以下是有關如何測試條件並處理它的快速原始示例。
void Main()
{
var filePath ="C:\\TEST.DAT";
if(!File.Exists(filePath)){ DisplayFileNotFoundError(filePath); }
try
{
var lines = GetFileLines(filePath);
if(lines == null) { DisplayFileNotFoundError(filePath);}
// do work with lines;
}
catch (Exception ex)
{
DisplayFileReadException(ex);
}
}
void DisplayErrorMessageToUser(string filePath)
{
Console.WriteLine("The file does not exist");
}
void DisplayFileReadException(Exception ex){
Console.WriteLine(ex.Message);
}
string[] GetFileLines(string filePath){
if(!File.Exists(filePath)){ return null; }
string[] lines;
try
{
lines = File.ReadLines(filePath);
return lines;
}
catch (FileNotFoundException fnf){
Trace.WriteLine(fnf.Message);
return null;
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
throw ex;
}
}
性能測試,FileNotFoundException異常VS File.Exists
void Main()
{
int max = 100000;
long[] feSampling = new long[max];
long[] exSampling = new long[max];
String pathRoot ="C:\\MISSINGFILE.TXT";
String path = null;
Stopwatch sw = new Stopwatch();
for (int i = 0; i < max; i++)
{
path = pathRoot + i.ToString();
sw.Start();
File.Exists(pathRoot);
sw.Stop();
feSampling[i] = sw.ElapsedTicks;
sw.Reset();
}
StreamReader sr = null;
sw.Reset();
for (int i = 0; i < max; i++)
{
path = pathRoot + i.ToString();
try
{
sw.Start();
sr = File.OpenText(path);
}
catch (FileNotFoundException)
{
sw.Stop();
exSampling[i] = sw.ElapsedTicks;
sw.Reset();
if(sr != null) { sr.Dispose();}
}
}
Console.WriteLine("Total Samplings Per Case: {0}", max);
Console.WriteLine("File.Exists (Ticsk) - Min: {0}, Max: {1}, Mean: {2}", feSampling.Min(), feSampling.Max(), feSampling.Average());
Console.WriteLine("FileNotFoundException (Ticks) - Min: {0}, Max: {1}, Mean: {2}", exSampling.Min(), exSampling.Max(), exSampling.Average());
}
你周圍有一個簡單的字符串賦值的嘗試。不會拋出異常。它可能需要圍繞在你的'ReadallLine'語句中,因爲這可能由於各種原因而失敗。 – Plutonix