How to read existing text files without defining path

后端 未结 8 1000
太阳男子
太阳男子 2020-12-14 05:53

Most of the examples shows how to read text file from exact location (f.e. \"C:\\Users\\Owner\\Documents\\test1.txt\"). But, how to read text files without writing full path

8条回答
  •  無奈伤痛
    2020-12-14 06:15

    This will load a file in working directory:

            static void Main(string[] args)
            {
                string fileName = System.IO.Path.GetFullPath(Directory.GetCurrentDirectory() + @"\Yourfile.txt");
    
                Console.WriteLine("Your file content is:");
                using (StreamReader sr = File.OpenText(fileName))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(s);
                    }
                }
    
                Console.ReadKey();
            }
    

    If your using console you can also do this.It will prompt the user to write the path of the file(including filename with extension).

            static void Main(string[] args)
            {
    
                Console.WriteLine("****please enter path to your file****");
                Console.Write("Path: ");
                string pth = Console.ReadLine();
                Console.WriteLine();
                Console.WriteLine("Your file content is:");
                using (StreamReader sr = File.OpenText(pth))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(s);
                    }
                }
    
                Console.ReadKey();
            }
    

    If you use winforms for example try this simple example:

            private void button1_Click(object sender, EventArgs e)
            {
                string pth = "";
                OpenFileDialog ofd = new OpenFileDialog();
    
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    pth = ofd.FileName;
                    textBox1.Text = File.ReadAllText(pth);
                }
            }
    

提交回复
热议问题