如果有可能,你应该尝试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