读取文本文件
try
{
// 创建一个 StreamReader 的实例来读取文件
// using 语句也能关闭 StreamReader
using (StreamReader sr = new StreamReader("c:/jamaica.txt"))
{
string line;
// 从文件读取并显示行,直到文件的末尾
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// 向用户显示出错消息
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
写入文本文件
string[] names = new string[] {"Zara Ali", "Nuha Ali"};
using (StreamWriter sw = new StreamWriter("names.txt"))
{
foreach (string s in names)
{
sw.WriteLine(s);
}
}
获取IIS上网站的文件夹路径:
string filePath = “/upload/txt/”;
HttpContext.Current.Server.MapPath(filePath);
//File.ReadAllLines()读取文件中所有行
string[] content = File.ReadAllLines(HttpContext.Current.Server.MapPath(filePath))
string[] content = File.ReadAllLines(HttpContext.Current.Server.MapPath(filePath)).Distinct().ToArray();