首页 > 解决方案 > 为什么我收到错误“找不到文件'C\Users\daylo\Onedrive\Desktop\VisualStudio\Total Sales\Total Sales\bin\Debug\Sales/txt'

问题描述

一个类的问题要求创建一个应用程序,该应用程序将数字从文件读取到数组并计算数组值的总和。但是在运行程序时,我收到此错误:

找不到文件“C\Users\daylo\Onedrive\Desktop\VisualStudio\Total Sales\Total Sales\bin\Debug\Sales/txt”。

我尝试将实际文本文件复制并粘贴到 Program.cs 中,但出现相同的错误。我认为问题是由于文件的位置造成的,但我不确定如何有效地对其进行故障排除。

这是代码:

public Form1()
    {
        InitializeComponent();
    }

    private void calcTotalBtn_Click(object sender, EventArgs e)
    {
        try
        {
            string[] allLines = File.ReadAllLines("Sales.txt");
            double[] numbers = new double[allLines.Length];
            int counter = 0;
            double sum = 0;

            foreach (string value in allLines)
            {
                numbers[counter] = Convert.ToDouble(value);
                sum += numbers[counter];
                outPutListBox.Items.Add(numbers[counter]);
                counter++;
            }

            outPutListBox.Items.Add("\nTotal: " + sum.ToString("n"));
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

标签: c#

解决方案


File.ReadAllLines("Sales.txt");

表示读取当前工作目录下的文件。这是一种糟糕的做法,因为只有明确更改为当前工作目录才能保证当前工作目录。作为最佳实践,请始终提供完整路径和文件名。


推荐阅读