我收到错误:
无法找到文件'C:\ Program Files(x86)\ IIS Express \ Cobb_County_Traffic_Counts.csv'。'
我的文件位于主项目文件中(如下所示),所以我不知道它是如何找不到的。
以下是我正在运行的代码:
private const string Path = (@"Cobb_County_Traffic_Counts.csv");
protected void Page_Load(object sender, EventArgs e)
{
loadCSV(sender, e);
}
protected void loadCSV(object sender, EventArgs e)
{
List<String[]> fileContent = new List<string[]>();
using (StreamReader reader = new StreamReader(Path)) // mind the encoding - UTF8
using (TextFieldParser parser = new TextFieldParser(reader))
{
parser.TrimWhiteSpace = true; // if you want
parser.Delimiters = new[] { "," };
parser.HasFieldsEnclosedInQuotes = true;
while (!parser.EndOfData)
{
string[] line = parser.ReadFields();
fileContent.Add(line);
Console.WriteLine(line);
}
}
}
答案 0 :(得分:2)
请使用Server.MapPath()
获取实际路径。您正在将文件解析为IIS安装目录,因为它是运行IIS express可执行文件的相对路径。
List<String[]> fileContent = new List<string[]>();
using (StreamReader reader = new StreamReader(Server.MapPath("~/" + Path))) // mind the encoding - UTF8
using (TextFieldParser parser = new TextFieldParser(reader))
{
parser.TrimWhiteSpace = true; // if you want
parser.Delimiters = new[] { "," };
parser.HasFieldsEnclosedInQuotes = true;
while (!parser.EndOfData)
{
string[] line = parser.ReadFields();
fileContent.Add(line);
Console.WriteLine(line);
}
}
}