【问题标题】:Exception related to relative paths与相对路径相关的异常
【发布时间】:2017-03-16 18:18:32
【问题描述】:

我正在开发一个 C# 锐利的控制台应用程序。我遇到了以下与相对路径相关的错误,我尝试将调试设置从 anyCPU 更改为 x86,但这不起作用。有人可以指出我正确的方向。谢谢

public static void ReadOrders(string pOrderDirectory)
        {
            // This exception is already thrown by <code>Directory.GetFiles()</code> but caught earlier here to allow 
            // the option of throwing an app-specific exception
            if (!Directory.Exists(pOrderDirectory))
            {
                throw new DirectoryNotFoundException("Unable to find input directory for orders: " + pOrderDirectory); //ran into the exception here.
            }

            // Process the list of files found in the directory.
            string[] oOrderFilenames = Directory.GetFiles(pOrderDirectory, SalesTaxHelper.GetConfigurationValue(CONFIG_KEY_FILE_SEARCH_PATTERN));

            if (oOrderFilenames.Length < 1)
            {
                throw new IOException("No orders found in input directory");
            }

            foreach (var oOrderFile in oOrderFilenames)
            {
                var oOrderProcessor = new Order();

                var oOrderLineItems = File.ReadAllLines(oOrderFile);
                foreach (var oLineItem in oOrderLineItems)
                {
                    oOrderProcessor.AddLineItem(oLineItem);
                }

                Console.WriteLine(oOrderProcessor.PrintInvoice());
            }

            Console.WriteLine("======================================");
            Console.WriteLine("PROCESSED ALL INPUT FILES IN DIRECTORY");
        }

异常:找不到订单的输入目录:

谢谢, 哈里

【问题讨论】:

  • 可能与权限和访问该位置有关?
  • 目录是否存在?传递给函数的pOrderDirectory 的值是多少?
  • pOrderDirectory 的值必须用一个包含 3 个文本文件的输入文件夹填充,目前它没有读取它们
  • @Hari 但pOrderDirectory 实际上是什么样子的?它是完全合格的有效路径吗,例如“C:\用户\哈里\输入\文件夹?” ...或“/stuff/here/”或完全不同的东西?异常告诉您它找不到您指定的路径。确保您指定的路径是函数的正确格式。
  • 我希望它看起来像“/input”,但是它没有填充任何东西

标签: c# exception directory


【解决方案1】:

好的,所以请确保将您的文件夹命名为 input 放在项目的 bin > Debug 文件夹中,如果您设置了

pOrderDirectory = "input"

它应该找到文件夹。它会找到该文件夹​​的原因是因为您正在调试模式下构建,因此当您像我一样使用简单的字符串指定路径时,它将成为搜索文件夹的默认位置。

请注意,如果您更改为 Release,它将找不到您的文件夹,因为您的文件夹在 Debug 中。

【讨论】:

  • 真的应该有一个 else 所以如果目录不存在你不会得到异常: if (!Directory.Exists(pOrderDirectory)) { throw new DirectoryNotFoundException("Unable to find input directory for orders : " + pOrderDirectory); //在这里遇到异常。 } else { 其余代码}
  • 好吧,他的其余代码使用该文件夹来运行,所以如果它没有找到它,它可能不应该继续。
猜你喜欢
  • 1970-01-01
  • 2012-01-11
  • 2018-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
相关资源
最近更新 更多