XML 序列化 IOException 未处理

发布于 2024-10-18 22:28:49 字数 2677 浏览 2 评论 0原文

我有以下代码用于序列化标签的内容。当我按下“保存”按钮时,会生成一个 xml 文件。当我选择相同的 xml 文件后按“加载”按钮时,发生错误,IOException 未处理,该进程无法访问文件“C:\datasaved.xml”,因为它正在被另一个进程使用。我的代码有什么问题吗? 谢谢。

public class FormSaving
    {
        private string major;

        public string Majorversion
        {
            get;

            set;

        }
    }



    private void SaveButton_Click(object sender, RoutedEventArgs e)
    {
        string savepath;
        SaveFileDialog DialogSave = new SaveFileDialog();
        // Default file extension
        DialogSave.DefaultExt = "txt";
        // Available file extensions
        DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
        // Adds a extension if the user does not
        DialogSave.AddExtension = true;
        // Restores the selected directory, next time
        DialogSave.RestoreDirectory = true;
        // Dialog title
        DialogSave.Title = "Where do you want to save the file?";
        // Startup directory
        DialogSave.InitialDirectory = @"C:/";
        DialogSave.ShowDialog();
        savepath = DialogSave.FileName;
        DialogSave.Dispose();
        DialogSave = null;

        FormSaving abc = new FormSaving();
        abc.Majorversion = MajorversionresultLabel.Content.ToString();
        FileStream savestream = new FileStream(savepath, FileMode.Create);
        XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
        serializer.Serialize(savestream, abc);
    }

    private void LoadButton_Click(object sender, RoutedEventArgs e)
    {


        Stream checkStream = null;
        Microsoft.Win32.OpenFileDialog DialogLoad = new Microsoft.Win32.OpenFileDialog();
        DialogLoad.Multiselect = false;
        DialogLoad.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
        if ((bool)DialogLoad.ShowDialog())
        {
            try
            {
                if ((checkStream = DialogLoad.OpenFile()) != null)
                {
                    loadpath = DialogLoad.FileName;
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }
        else
        {
            System.Windows.MessageBox.Show("Problem occured, try again later");
        }

        FormSaving abc;
        FileStream loadstream = new FileStream(loadpath, FileMode.Open);
        XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
        abc = (FormSaving)serializer.Deserialize(loadstream);
        loadstream.Close();
        MajorversionresultLabel.Content = abc.Majorversion;
    }

i have the following code used to serialize a label's content. When i press the "save" button, an xml file is generated. When press the "load" button after i select the same xml file, an error occured, IOexception was unhandled, The process cannot access the file 'C:\datasaved.xml' because it is being used by another process. Is there anything wrong with my code?
Thanks.

public class FormSaving
    {
        private string major;

        public string Majorversion
        {
            get;

            set;

        }
    }



    private void SaveButton_Click(object sender, RoutedEventArgs e)
    {
        string savepath;
        SaveFileDialog DialogSave = new SaveFileDialog();
        // Default file extension
        DialogSave.DefaultExt = "txt";
        // Available file extensions
        DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
        // Adds a extension if the user does not
        DialogSave.AddExtension = true;
        // Restores the selected directory, next time
        DialogSave.RestoreDirectory = true;
        // Dialog title
        DialogSave.Title = "Where do you want to save the file?";
        // Startup directory
        DialogSave.InitialDirectory = @"C:/";
        DialogSave.ShowDialog();
        savepath = DialogSave.FileName;
        DialogSave.Dispose();
        DialogSave = null;

        FormSaving abc = new FormSaving();
        abc.Majorversion = MajorversionresultLabel.Content.ToString();
        FileStream savestream = new FileStream(savepath, FileMode.Create);
        XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
        serializer.Serialize(savestream, abc);
    }

    private void LoadButton_Click(object sender, RoutedEventArgs e)
    {


        Stream checkStream = null;
        Microsoft.Win32.OpenFileDialog DialogLoad = new Microsoft.Win32.OpenFileDialog();
        DialogLoad.Multiselect = false;
        DialogLoad.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
        if ((bool)DialogLoad.ShowDialog())
        {
            try
            {
                if ((checkStream = DialogLoad.OpenFile()) != null)
                {
                    loadpath = DialogLoad.FileName;
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }
        else
        {
            System.Windows.MessageBox.Show("Problem occured, try again later");
        }

        FormSaving abc;
        FileStream loadstream = new FileStream(loadpath, FileMode.Open);
        XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
        abc = (FormSaving)serializer.Deserialize(loadstream);
        loadstream.Close();
        MajorversionresultLabel.Content = abc.Majorversion;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧话新听 2024-10-25 22:28:49

这是最直接的问题:

FileStream savestream = new FileStream(savepath, FileMode.Create);
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, abc);

您没有关闭流,因此无法重新打开文件进行读取。使用 using 语句:

using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
    XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
    serializer.Serialize(savestream, abc);
}

加载文件时也应该采取相同的方法,而不是使用当前的显式调用 Close...代码中,如果反序列化时发生异常,您将不会关闭流。

通过Dialog.OpenFile打开文件,但没有关闭该流......为什么还要费心打开它两次呢?只需从您打开的流中读取即可。

最后(目前)您捕获了一个异常(盲目地,不考虑哪些异常确实值得尝试处理),但无论如何都继续。如果您捕获到异常,则该方法的最后部分很可能无法正确执行,因此您应该返回自己抛出另一个异常。

This is the most immediate problem:

FileStream savestream = new FileStream(savepath, FileMode.Create);
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, abc);

You're not closing the stream, so the file can't be reopened for read. Use a using statement:

using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
    XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
    serializer.Serialize(savestream, abc);
}

You should take the same approach when loading the file as well, instead of calling Close explicitly... with your current code, if an exception occurs when deserializing, you won't be closing the stream.

You're also opening the file via Dialog.OpenFile, but not closing that stream... and why bother opening it twice? Just read from the stream you've opened.

Finally (for the moment) you're catching an exception (blindly, with no regard for which exceptions are really worth trying to handle) but then continuing regardless. If you've caught an exception, chances are the last part of the method won't execute correctly, so you should either return or throw another exception yourself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文