问题
I have got this read file code from microsoft
@"C:\Users\computing\Documents\mikec\assignment2\task_2.txt"
That works fine when im working on it, but when i am to hand in this assignment my lecturer isn't going to have the same directory as me.
So i was wondering if there is a way to read it from just the file the program is held in?.
I was thinking i could add it as a resource but im not sure if that is the correct way for the assignment it is meant to allow in any file.
Thanks
回答1:
You can skip the path - this will read file from the working directory of the program.
Just @"task_2.txt"
will do.
UPDATE: Please note that method won't work in some circumstances. If your lecturer uses some automated runner (script, application whatsoever) to verify your app then @ken2k's solution will be much more robust.
回答2:
If you want to read a file from the directory the program is in, then use
using System.IO;
...
string myFileName = "file.txt";
string myFilePath = Path.Combine(Application.StartupPath, myFileName);
EDIT: More generic solution for non-winforms applications:
string myFilePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), myFileName);
回答3:
If it is a command line application, you should take the file name as a command line argument instead of using a fixed path. Something along the lines of;
public static void Main(string[] args)
{
if (args == null || args.Length != 1)
{
Console.WriteLine("Parameters are not ok, usage: ...");
return;
}
string filename = args[0];
...
...should let you get the filename from the command.
回答4:
You could use the GetFolderPath method to get the documents folder of the current user:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
and to exemplify:
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);
回答5:
Use the relative path.
you can put your file inside the folder where your application resides. you can use Directory.GetCurrentDirectory().ToString() method to get the current folder of the application in. if you put your files inside a sub folder you can use Directory.GetCurrentDirectory().ToString() + "\subfolderName\"
File.OpenRead(Directory.GetCurrentDirectory().ToString() + "\fileName.extension")
StreamReader file = new StreamReader(File.OpenRead(Directory.GetCurrentDirectory().ToString() + ""));
string fileTexts = file.ReadToEnd();
来源:https://stackoverflow.com/questions/8861854/read-a-file-from-an-unknown-location