Search code examples
c#directoryresourcesenvironment-variablesprocess.start

Get path to it and run process


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");

Solution

  • 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.