C#中遍历文件夹中文件的最简单方法是什么?

6
我想编写一个程序,使用包含相关文件路径的配置文件来浏览本地文件系统。我的问题是:在C#中执行文件I/O(这将从桌面应用程序到服务器再返回)和文件系统导航时,最佳实践是什么?
我知道如何使用谷歌,并且已经找到了几种解决方案,但我想知道哪个函数最为健壮和灵活。此外,如果有关于C#文件I/O异常处理的任何提示,那也将非常有帮助。
4个回答

13

你不需要使用单独的库,可以使用 System.IO 命名空间中的类,例如 File, FileInfo, Directory, DirectoryInfo。这里是一个简单的示例:

var d = new DirectoryInfo(@"c:\");
foreach(FileInfo fi in d.GetFiles())
    Console.WriteLine(fi.Name);

抱歉,我是C#的新手。我的意思是我找到了多种技术,但似乎它们的方法都包含在System.IO.File类中。 - badpanda
@badpanda:你选择哪个类/方法取决于你尝试做什么的具体情况。你能提供更多细节吗? - D'Arcy Rittich
当然。我需要读取文件以后发送到 Web 服务。这些文件很可能是 InfoPath 文件。 - badpanda
如果相关的话,我还需要一些文件属性的信息。 - badpanda
请参考http://www.csharp-examples.net/file-attributes/,了解如何访问属性的示例。 - D'Arcy Rittich

3

你提到的各种库是指哪些?

我会建议你主要使用System.IO.Directory等相关库,它拥有你所需要的一切功能。

就像下面这样:

foreach (var file in System.IO.Directory.GetFiles(@"C:\Yourpath"))
{
    // Do ya thang.
}

2

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
    }
}

2

System.IO 命名空间中有许多你可以使用的类,包括 FileFileInfoDirectoryDirectoryInfo

至于实践...像任何 IO 操作一样,请确保关闭你打开的任何流。你还可能需要使用一个 Disposable 对象,因此请了解 using 关键字。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接