【发布时间】:2016-10-25 16:11:54
【问题描述】:
我正在尝试将文件读入字符串,然后将其发送到另一个应用程序。
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:\text.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
我收到错误:
The file could not be read:
Could not find file 'c:\users\andymarkmn\documents\visual studio 2015\Projects\FileApplication\FileApplication\bin\Debug\text.txt'.
我也尝试将文件放入 bin 调试文件夹中。
如何确保代码有效?
编辑:按照建议,我尝试使用不同的方法。
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string filepath = "c:\\text.txt";
try
{
string lines = File.ReadAllText(filepath);
Console.Write(lines);
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
我仍然收到错误:
The file could not be read:
Could not find file 'c:\text.txt'.
【问题讨论】:
-
无助于解决问题,但
File.ReadAllLines会更容易 -
错误消息的文件名与您尝试阅读的文件名不同。
-
@stuartd 嗨,你能不能也给一个代码示例。我是 c# 和 .net 堆栈的新手。
-
你有这个文件吗
c:\text.txt -
string[] lines = File.ReadAllLines(filePath)- docs,或者File.ReadAllText,如果你只想将文本作为一个大字符串
标签: c# visual-studio file error-handling console