繁体   English   中英

从本地文件夹中读取文本文件

[英]Read a text file from local folder

我想从我的本地目录中读取一个文本文件,我将文本文件添加到我的c#解决方案中,因此它会在部署时被复制..但是我如何打开它? 我一直在搜索,但所有的例子都假设我有一个C:\\ textfile.txt:

我试过只读文件

if (File.Exists("testfile.txt"))
{
   return true;
}

那没用。 然后我尝试了:

if (File.Exists(@"\\TextConsole\testfile.txt"))
{
   return true;
}

但仍然不会打开它..任何想法?

仅仅因为您将它添加到您的解决方案并不意味着文件被放入您的输出Build目录中。 如果要使用相对路径,请确保在构建期间将TextFile复制到输出目录。 要执行此操作,请在解决方案资源管理器中转到文本文件的属性,并将“ Copy to Output Directory设置为“ Always或“ Copy if newer

然后你可以使用

File.Open("textfile.txt");

在您进行检查后,您需要使用以下其中一项

 string path = @"\\TextConsole\testfile.txt";
 if (File.Exists(path))
 {
  FileStream fileStream = File.OpenRead(path); // or
  TextReader textReader = File.OpenText(path); // or
  StreamReader sreamReader = new StreamReader(path);
 }

此示例使用StreamReader类的ReadLine方法将文本文件的内容(一次一行)读入字符串。 每个文本行都存储在字符串行中并显示在屏幕上。

  int counter = 0;
  string line;

// Read the file and display it line by line.
System.IO.StreamReader file =  new System.IO.StreamReader("c:\\test.txt");

while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
   counter++;
}

file.Close();

// Suspend the screen.
Console.ReadLine();

参考http://msdn.microsoft.com/en-us/library/aa287535%28v=vs.71%29.aspx

如果文件确实在c:\\textfile.txt ,您可以这样找到它:

if (File.Exists(@"c:\testfile.txt"))
{
   return true;
}

但是您应该使用Path.Combine来构建嵌套文件路径,并使用DriveInfo来处理驱动器详细信息。

正如Bobby在评论中提到的 PathCombine ,在当前文件夹中使用简单的PathCombine为我工作:

string txtPath = Path.Combine(Environment.CurrentDirectory, "testfile.txt")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM