【问题标题】:Is it ok to .OpenFile() a file that is already Open?.OpenFile() 一个已经打开的文件可以吗?
【发布时间】:2016-10-21 03:15:53
【问题描述】:

这不需要任何实际的问题解决。只是想知道事物的本质。

我注意到,如果我连续两次触发此事件,两次都选择同一个文件,即使我从未明确关闭该文件,我也不会收到任何错误。当 ReadLine 到达文件末尾时文件是否会自动关闭,或者只要它由同一个应用程序打开,就可以尝试打开已经打开的文件?

 private void uIDownloadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int lineNum = 1;
            using (OpenFileDialog dlgOpen = new OpenFileDialog())
                try
                {
                    // Default file extension
                    dlgOpen.DefaultExt = "*.hex";
                    // SaveFileDialog title
                    dlgOpen.Title = "Download UI Image";
                    // Available file extensions
                    dlgOpen.Filter = "Hex Files (*.hex)|*.hex|All Files (*.*)|*.*";
                    // Show SaveFileDialog box and save file
                    if (dlgOpen.ShowDialog() == DialogResult.OK)
                    {
                        dlgOpen.OpenFile();
                        string file = dlgOpen.FileName;
                        StreamReader reader = new StreamReader(file);
                        var result = MessageBox.Show("Please confirm the file:" + file, "Confirm", MessageBoxButtons.OKCancel);
                        if (result == DialogResult.OK)
                        {
                            commandConstruct(OP.SETSTATE, DEV.SPI_DEV, "1" , "");
                            if (ready == true)
                            {
                                using (reader)
                                {

                                    string check;
                                    bool verified = true;
                                    do
                                    {
                                        check = reader.ReadLine();

                                    } while (check != null);
                                }
                            }
                        }

                    }
                }
                catch (Exception errorMsg)
                {
                    MessageBox.Show(errorMsg.Message);
                }
        }

【问题讨论】:

    标签: c# winforms streamreader openfiledialog


    【解决方案1】:

    如果你将它捆绑在 Using() 中,那么你不必担心,如果没有,它不会抛出任何错误,但只是内存块仍将被占用。因此,如果您认为文件非常大,并且您必须对内存管理进行控制,那么最好使用 Using() 进行捆绑

    【讨论】:

      【解决方案2】:

      StreamReader 应在读取文件后关闭。如果您打开文件只是为了阅读,应该没问题。请参阅link

      using (StreamReader r = new StreamReader("file.txt"))
      {
        allFileText = r.ReadToEnd();
      }
      

      【讨论】:

        【解决方案3】:

        我发现“使用”会自行关闭它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-04-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多