【问题标题】:System.ObjectDisposedException Error on C# v4.0C# v4.0 上的 System.ObjectDisposedException 错误
【发布时间】:2012-09-24 09:39:57
【问题描述】:

我实现了这段代码: C# Processing Fixed Width Files

但由于我的工作 PC 运行 Windows XP,我不得不使用 C# v4.0 保存程序。不幸的是以下代码:

static string filePath = "";

public Main()
{
    InitializeComponent();
}

private void buttonLoadFile_Click(object sender, EventArgs e)
{
    DialogResult openFile = openFileDialog.ShowDialog();
    if (openFile == DialogResult.OK)
    {
        filePath = openFileDialog.FileName;
    }
}

private void buttonProcessFile_Click(object sender, EventArgs e)
{
    if (filePath == "")
    {
        MessageBox.Show("Load Fixed Width File First", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }
    else
    {
        if (textboxFilePath.Text == "")
        {
            MessageBox.Show("Enter CSV File Path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else
        {
            DialogResult result = DialogResult.No;

            if (File.Exists(filePath))
            {
                result = MessageBox.Show("Overwrite CSV File?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            }

            if (result == DialogResult.Yes)
            {
                var lines = File.ReadLines(filePath);

                var widthList = lines.First().GroupBy(c => c)
                                             .Select(g => g.Count())
                                             .ToList();

                var list = new List<KeyValuePair<int, int>>();

                int startIndex = 0;

                for (int i = 0; i < widthList.Count(); i++)
                {
                    var pair = new KeyValuePair<int, int>(startIndex, widthList[i]);
                    list.Add(pair);

                    startIndex += widthList[i];
                }

                var csvLines = lines.Select(line => string.Join(",",
                                    list.Select(pair => line.Substring(pair.Key, pair.Value))));

                File.WriteAllLines(textboxFilePath.Text, csvLines);

                MessageBox.Show("File Saved", "Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        }
    }
}

在 Windows XP 上运行并在 C# v4.0 中编译时出现此错误:

************** Exception Text **************
System.ObjectDisposedException: Cannot read from a closed TextReader.
   at System.IO.__Error.ReaderClosed()
   at System.IO.StreamReader.ReadLine()
   at System.IO.File.<InternalReadLines>d__0.MoveNext()
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.IO.File.InternalWriteAllLines(TextWriter writer, IEnumerable`1 contents)
   at System.IO.File.WriteAllLines(String path, IEnumerable`1 contents)
   at FixedWidthFiles.Main.buttonProcessFile_Click(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
    CodeBase: file:///C:/WINDOWS/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
FixedWidthFiles
    Assembly Version: 1.0.0.0
    Win32 Version: 1.0.0.0
    CodeBase: file:///C:/TEMP/FixedWidthFiles.exe
----------------------------------------
System.Windows.Forms
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.1 built by: RTMRel
    CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.1 built by: RTMRel
    CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.1 built by: RTMRel
    CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Core
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.1 built by: RTMRel
    CodeBase: file:///C:/WINDOWS/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------

有什么建议吗?

【问题讨论】:

  • 您显示的代码似乎与异常不匹配。例外提到Where。您的代码中没有Where
  • 你能试试另一个示例文件吗?
  • @DanielHilgarth - 用我实现的确切代码更新了帖子。对此深表歉意。

标签: c# objectdisposedexception


【解决方案1】:

来自MSDN文档

ReadLines 和 ReadAllLines 方法的区别如下: ReadLines,可以开始枚举之前的字符串集合 整个集合被退回;当您使用 ReadAllLines 时,您必须 等待返回整个字符串数组,然后才能访问 数组。因此,当您处理非常大的文件时, ReadLines 可以更高效。

更改您的代码,

var widthList = File.ReadLines(@"C:\input.txt").First().GroupBy(c => c)
                             .Select(g => g.Count())
                             .ToList();

或者使用

var lines = File.ReadAllLines(@"C:\input.txt");

var widthList = lines.First().GroupBy(c => c)
                             .Select(g => g.Count())
                             .ToList();

【讨论】:

  • 当然你必须使用ReadLines()方法但这里是bug
  • 这是天才发现,只发生在 .NET 4 上,但在 .NET 4.5 上运行良好
  • @AVD - 我猜这就是为什么它在使用 .Net 4.0 的 Windows XP 上对我不起作用的原因?
  • 确实如此。在我的网站上它的工作,因为我更新了 VS2010 - service pack1
  • @AVD - 我只是在我的工作电脑上安装 VS2010 SP1,然后会尝试你的建议,所以让我们看看会发生什么。
猜你喜欢
  • 2015-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-09
  • 2017-03-08
  • 2019-04-12
  • 2020-12-08
  • 2018-01-16
相关资源
最近更新 更多