简体   繁体   中英

How do i access and create txt files in the same directory as the program in c#

http://pastebin.com/DgpMx3Sx

Currently i have this, i need to find a way to make it so that as opposed to writing out the directory of the txt files, i want it to create them in the same location as the exe and access them.

basically i want to change these lines

string location = @"C:\Users\Ryan\Desktop\chaz\log.txt";
string location2 = @"C:\Users\Ryan\Desktop\chaz\loot.txt";

to something that can be moved around your computer without fear of it not working.

如果要将文件保存在与可执行文件相同的路径中,则可以使用以下命令获取目录:

string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

Normally you wouldn't do that, mostly because the install path will be found in the Program Files folders, which require Administrative level access to be modified. You would want to store it in the Application Data folder. That way it is hidden, but commonly accessible through all the users.

You could accomplish such a feat by:

string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullPath = Path.Combine(path, @"NameOfApplication");

With those first two lines you'll always have the proper path to a globally accessible location for the application.

Then when you do something you would simply combine the fullPath and the name of the file you attempt to manipulate with FileStream or StreamWriter .

If structured correctly it could be as simple as:

private static void WriteToLog(string file)
{
     string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
      string fullPath = Path.Combine(path, @"NameOfApplication");

     // Validation Code should you need it.

     var log = Path.Combine(fullPath, file);
     using(StreamWriter writer = new StreamWriter(log))
     {
          // Data
     }
}

You could obviously structure or make it better, this is just to provide an example. Hopefully this points you in the right direction, without more specifics then I can't be more help.

But this is how you can access data in a common area and write out to the file of your choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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