c# - 为什么我收到错误“找不到文件'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);
}
解决方案
File.ReadAllLines("Sales.txt");
表示读取当前工作目录下的文件。这是一种糟糕的做法,因为只有明确更改为当前工作目录才能保证当前工作目录。作为最佳实践,请始终提供完整路径和文件名。
推荐阅读
- tensorflow - 我训练了一个神经网络,但我找不到它的保存位置,我找不到任何 .meta 、 .index 、 .data 文件
- wordpress - 从过去 3 天开始,收到大量来自美国的垃圾邮件流量,如何阻止?
- sql - golang null.String 解码无法正常工作
- cordova - 我们有用于 aws-cognito-identity 的 cordova 插件吗?
- html - 在 HTML/CSS 中访问链接时使图像变为灰度
- angular - 添加解析器和动态布局组合后,Angular 8 组件不显示
- selenium - 获取“无法启动 Selenium 侦听器”。通过 saucelabs 运行 testcafe 脚本时出现错误消息
- android - 如何设置此微调器文本的字体(字体)?
- django - Django crispy-forms:带有 TextArea 字段的 2 列表单
- sql - 使用 SQL 检索已订购商品的总数量