2012-01-14 89 views
1

我有这个阅读微软从未知位置读取文件?

@"C:\Users\computing\Documents\mikec\assignment2\task_2.txt" 

文件代码即时通讯工作也就罢了,但是当我在这个任务交出我的讲师是不会有相同的目录中我工作正常。

所以我想知道是否有一种方法来从程序被保存在文件中读取?

我在想我可以将它作为资源添加,但我不知道这是否是任何文件允许的赋值的正确方法。

感谢

+0

也许只是我,但我真的没有得到什么是你的麻烦...... – 2012-01-14 11:21:06

+0

为什么不只是一个'FileBrowserDialog'? – 2012-01-14 11:23:47

回答

4

可以跳过路径 - 这会从程序的工作目录中读取文件。

只需要@"task_2.txt"就可以。

UPDATE:请注意该方法在某些情况下不起作用。如果您的讲师使用一些自动化的跑步者(脚本,应用程序)来验证您的应用程序,那么@ ken2k的解决方案将更加健壮。

+0

如果该文件不在工作目录内,该怎么办? – 2012-01-14 11:23:26

+3

@DarinDimitrov但他的问题表明它是 – 2012-01-14 11:25:59

+0

那么当然它不会起作用。我只是提出了一种可能的方法来解决这个问题。 – 2012-01-14 11:30:34

0

你可以使用GetFolderPath方法来获取当前用户的文件夹:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) 

,并举例说明:

string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
string file = Path.Combine(myDocuments, @"mikec\assignment2\task_2.txt"); 
// TODO: do something with the file like reading it for example 
string contents = File.ReadAllText(file); 
+1

他询问程序所在的地方,而不是我的文档 – 2012-01-14 11:25:30

2

如果你想读取文件从程序所在的目录中,然后使用

using System.IO; 
... 
string myFileName = "file.txt"; 
string myFilePath = Path.Combine(Application.StartupPath, myFileName); 

编辑:非的WinForms应用 更通用的解决方案:

string myFilePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), myFileName); 
+0

Application.StartupPath可能与文档文件夹不同。该应用程序可以部署在例如Program Files中。 – 2012-01-14 11:23:05

+2

你说得对,但我不认为OP想专门使用Documents文件夹。 – ken2k 2012-01-14 11:25:07

1

如果是命令行应用程序,则应该将文件名作为命令行参数,而不是使用固定路径。某事沿着;

public static void Main(string[] args) 
{ 
    if (args == null || args.Length != 1) 
    { 
     Console.WriteLine("Parameters are not ok, usage: ..."); 
     return; 
    } 

    string filename = args[0]; 

... 

...应该让你从命令中获取文件名。

0

使用相对路径。

您可以将您的文件放入应用程序所在的文件夹中。 你可以使用Directory.GetCurrentDirectory()。ToString()方法获取应用程序的当前文件夹。如果你把你的文件放到你可以使用的子文件夹中 Directory.GetCurrentDirectory()。ToString()+“\ subfolderName “

File.OpenRead(Directory.GetCurrentDirectory().ToString() + "\fileName.extension") 


StreamReader file = new StreamReader(File.OpenRead(Directory.GetCurrentDirectory().ToString() + "")); 
      string fileTexts = file.ReadToEnd(); 
相关问题