0

How to get path by environment variable to get file:

string path = (@"%ProgramData%\\myFolder\\textdoc.txt");

to run file by environment variable path:

 Process.Start(@"%ProgramData%\\myFolder\\file.exe");

1 Answers1

0

Here is how you can create folder,file and write text in it. Once file is created and written, it will be opened in notepad.

private void button1_Click(object sender, EventArgs e)
    {
        string basePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
        string myDir = Path.Combine(basePath, "myFolder");
        if (!Directory.Exists(myDir))
        {
            Directory.CreateDirectory(myDir);
        }
        string myFile = Path.Combine(myDir, "textdoc.txt");
        using (FileStream fs = File.OpenWrite(myFile))
        {
            using (StreamWriter wrtr = new StreamWriter(fs, Encoding.UTF8))
            {
                wrtr.WriteLine("This is my text");
            }
        }

        Process.Start("notepad.exe", myFile);

    }

Note : Way file is created and written in above code will always overwrite file content. If you need to append new content then you should use different constructor of StreamWriter and pass append parameter as true.

Also you need admin permission to create folder/file inside "ProgramData" folder.

Pankaj Kapare
  • 7,486
  • 5
  • 40
  • 56
  • Hello, I'm going to check your answer, just let me see, but before I want to ask you about advice, as you said about admin permission to writing into the program data. what is the best way to write folder/file for such cases and make it useful in executable for other users? I have only text documents and one .exe file there. So maybe program data is not the good way for this case, because I'm not sure how to figure out with permission, for example this way @"%ProgramData%\\myFolder\\textdoc.txt" when I'm create path for executable? –  Dec 06 '16 at 19:15
  • You can use any other directory other than ProgramData, Program Files etc which is accessible to all your users. – Pankaj Kapare Dec 06 '16 at 19:18
  • Only question I got, what is notepad.exe in `Process.Start("notepad.exe", myFile);`? –  Dec 06 '16 at 20:48