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

发布于 2024-09-04 07:46:22 字数 189 浏览 5 评论 0原文

我尝试编写一个程序,使用包含相关文件路径的配置文件来导航本地文件系统。我的问题是:在 C# 中执行文件 I/O(这将是从桌面应用程序到服务器并返回)和文件系统导航时使用的最佳实践是什么?

我知道如何谷歌,并且找到了几种解决方案,但我想知道各种功能中哪一种最强大和灵活。同样,如果有人有任何有关 C# 文件 I/O 异常处理的提示,那也会非常有帮助。

I trying to write a program that navigates the local file system using a config file containing relevant filepaths. My question is this: What are the best practices to use when performing file I/O (this will be from the desktop app to a server and back) and file system navigation in C#?

I know how to google, and I have found several solutions, but I would like to know which of the various functions is most robust and flexible. As well, if anyone has any tips regarding exception handling for C# file I/O that would also be very helpful.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

殤城〤 2024-09-11 07:46:23

您不需要单独的库,请使用 System.IO 命名空间中的类,例如 FileFileInfoDirectory,<代码>目录信​​息。一个简单的例子:

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

You don't need a separate library, use the classes in the System.IO namespace like File, FileInfo, Directory, DirectoryInfo. A simple example:

var d = new DirectoryInfo(@"c:\");
foreach(FileInfo fi in d.GetFiles())
    Console.WriteLine(fi.Name);
梦年海沫深 2024-09-11 07:46:23

您在谈论哪些不同的图书馆?

我几乎会坚持使用 System.IO.Directory 等。它拥有您需要的一切。

像这样的东西:

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

What various libraries are you talking about?

I would pretty much stick to System.IO.Directory and such. It has everything you need.

Something like:

foreach (var file in System.IO.Directory.GetFiles(@"C:\Yourpath"))
{
    // Do ya thang.
}
缺⑴份安定 2024-09-11 07:46:23

您可以在 System.IO 命名空间中使用各种类,包括 FileFileInfoDirectory目录信息

至于实践......与任何 IO 一样,请确保关闭所有打开的流。您可能还需要利用 Disposable 对象,因此请查看 using 关键字。

There are various classes you can use in the System.IO namespace, including File, FileInfo, Directory, and DirectoryInfo.

As for practices... as with any IO, make sure you close any streams you open. You also may need to utilize a Disposable object, so look into the using keyword.

久随 2024-09-11 07:46:23

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 is all you need :)

As regards exception handling. Unless we are expecting an exception, we should never catch it. Truly unexpected exceptions should go unhandled. [looks guilty] ok, the only exception is at the highest level, and only for reporting purposes, such as

// 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);
    }

}

If you are expecting an exception then one of the following is acceptable

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

or

// 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
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文