在c#中怎么打开已经存在的文件?

解决方案 »

  1.   

    refer:
    //读取bin目录下的test.txt文件
                using (FileStream fs = File.Open("test.txt", FileMode.OpenOrCreate))
                {
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        while (sr.Read() > 0)
                        {
                            Console.WriteLine(sr.ReadLine());
                        }
                    }
                }
      

  2.   


    你可以利用文件流来实现它 如下示例:class FileReadDemo
    {
    public static void Main() 
    {
    string path;
    Console.WriteLine (
                                    "输入要读取的文件名。指定带路径的完整名称:");
    path = Console.ReadLine ();
    try
    {
           if (!File.Exists(path))
    {
    Console.WriteLine("文件不存在");
    }
    else
    {
    // 打开流以进行读取。 //创建一个 byte 数组以读取数据 
    byte[] arr = new byte[100];
    UTF8Encoding data = new UTF8Encoding(true);
            //继续读文件直到读取文件中的所有数据
    while (fs.Read(arr,0,arr.Length) > 0) 
    {
    Console.WriteLine(data.GetString(arr));
    }
    }
       }
      catch(Exception ex)
    {
    Console.WriteLine(“发生错误:" + ex.Message);
    }
      }
    }
      

  3.   

    LZ说的是打开文件,不是读取文件吧?
    System.Diagnostics.Process.Start(path);
      

  4.   

    猜测可能需要的是这个
    http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspx
    private void button1_Click(object sender, System.EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();    openFileDialog1.InitialDirectory = "c:\\" ;
        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
        openFileDialog1.FilterIndex = 2 ;
        openFileDialog1.RestoreDirectory = true ;    if(openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if ((myStream = openFileDialog1.OpenFile()) != null)
                {
                    using (myStream)
                    {
                        // Insert code to read the stream here.
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }
    }