C#获取路径、路径拼接、判断文件(夹)是否存在

C#获取exe路径,路径拼接,判断文件(夹)是否存在等常用功能总结:

           //1...\bin\Debug
            string path1 = Directory.GetCurrentDirectory();//exe所在目录。
            textBox1.Text += "1 "+path1+"\r\n";
            //2...\bin\Debug
            string path2 = System.Environment.CurrentDirectory;//exe所在目录
            textBox1.Text += "2 " + path2 + "\r\n";
            //3...\bin\Debug
            string path3 = System.Windows.Forms.Application.StartupPath;//exe所在目录
            textBox1.Text += "3 " + path3 + "\r\n";
            //4...\bin\Debug\
            string path4 = System.AppDomain.CurrentDomain.BaseDirectory;//exe所在目录。末尾带“\”
            textBox1.Text += "4 " + path4 + "\r\n";
            //5.../bin/Debug/...exe
            string path5 = System.Windows.Forms.Application.ExecutablePath;//exe全路径
            textBox1.Text += "5 " + path5 + "\r\n";
            //6...\bin\Debug\
            string path6 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//exe所在目录。末尾带“\”
            textBox1.Text += "6 " + path6 + "\r\n";
            //7...\bin\Debug\...exe
            string path7 = this.GetType().Assembly.Location;//.exe全路径
            textBox1.Text += "7 " + path7 + "\r\n";
            //8...\bin\Debug\...vshost.exe
            string path8 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;//获取.vshost.exe全路径
            textBox1.Text += "8 " + path8 + "\r\n";

            //路径拼接
            string path9 = System.IO.Path.Combine(Directory.GetCurrentDirectory(),"Data");
            textBox1.Text += "9 " + path9 + "\r\n";

            //判断文件夹是否存在,不存在则创建
            if(!Directory.Exists(path9))
            {
                Directory.CreateDirectory(path9);
            }
            //判断文件是否存在,不存在则创建
            string fileName = System.IO.Path.Combine(path9,"test.txt");
            if (!File.Exists(fileName))
            {
                File.Create(fileName);
            }

运行结果:


路径
创建的文件(夹)

你可能感兴趣的:(C#获取路径、路径拼接、判断文件(夹)是否存在)