我想编写一个程序,使用包含相关文件路径的配置文件来浏览本地文件系统。我的问题是:在C#中执行文件I/O(这将从桌面应用程序到服务器再返回)和文件系统导航时,最佳实践是什么?
我知道如何使用谷歌,并且已经找到了几种解决方案,但我想知道哪个函数最为健壮和灵活。此外,如果有关于C#文件I/O异常处理的任何提示,那也将非常有帮助。
我知道如何使用谷歌,并且已经找到了几种解决方案,但我想知道哪个函数最为健壮和灵活。此外,如果有关于C#文件I/O异常处理的任何提示,那也将非常有帮助。
你不需要使用单独的库,可以使用 System.IO
命名空间中的类,例如 File
, FileInfo
, Directory
, DirectoryInfo
。这里是一个简单的示例:
var d = new DirectoryInfo(@"c:\");
foreach(FileInfo fi in d.GetFiles())
Console.WriteLine(fi.Name);
你提到的各种库是指哪些?
我会建议你主要使用System.IO.Directory
等相关库,它拥有你所需要的一切功能。
就像下面这样:
foreach (var file in System.IO.Directory.GetFiles(@"C:\Yourpath"))
{
// Do ya thang.
}
System.IO
就是你所需要的 :)
关于异常处理。除非我们期望出现异常,否则不应该捕获它。真正意外的异常应该未经处理。[看起来有点内疚] 好吧,唯一的例外是在最高级别上,并且仅用于报告目的,例如
// assuming console program, but every application Console, WinForm,
// Wpf, WindowsService, WebService, WcfService has a similar entry point
class Program
{
// assume log4net logging here, but could as easily be
// Console.WriteLine, or hand rolled logger
private static readonly ILog _log = LogManager.GetLogger (typeof (Program));
static void Main (string[] args)
{
AppDomain.CurrentDomain.UnhandledException +=
CurrentDomain_UnhandledException;
}
private static void CurrentDomain_UnhandledException (
object sender,
UnhandledExceptionEventArgs e)
{
_log.
Fatal (
string.Format (
"Unhandled exception caught by " +
"'CurrentDomain_UnhandledException'. Terminating program.",
e.ExceptionObject);
}
}
如果您期望出现异常,则以下情况是可以接受的:
// example of first option. this applies ONLY when there is a
// well-defined negative path or recovery scenario
public void SomeFunction ()
{
try
{
string allText = System.IO.File.ReadAllText ();
}
// catch ONLY those exceptions you expect
catch (System.ArgumentException e)
{
// ALWAYS log an error, expected or otherwise.
_log.Warn ("Argument exception in SomeFunction", e);
// if the use-case\control flow is recoverable, invoke
// recovery logic, preferably out of try-catch scope
}
}
或者
// example of second option. this applies ONLY when there is no
// well defined negative path and we require additional information
// on failure
public void SomeFunction ()
{
try
{
string allText = System.IO.File.ReadAllText ();
}
// catch ONLY those exceptions you expect
catch (System.ArgumentException innerException)
{
// do whatever you need to do to identify this
// problem area and provide additional context
// like parameters or what have you. ALWAYS
// provide inner exception
throw new SomeCustomException (
"some new message with extra info.",
maybeSomeAdditionalContext,
innerException);
// no requirement to log, assume caller will
// handle appropriately
}
}
在 System.IO
命名空间中有许多你可以使用的类,包括 File
、FileInfo
、Directory
和 DirectoryInfo
。
至于实践...像任何 IO 操作一样,请确保关闭你打开的任何流。你还可能需要使用一个 Disposable
对象,因此请了解 using
关键字。