文件保存中的操作异常无效

时间:2016-07-04 14:12:32

标签: c# file

我有这段代码,我不知道为什么会弹出这条错误信息:

  

“无效的操作异常未被用户代码处理”。

按下保存按钮时出现此错误。

此程序的目的是将文本从Mytest.txt文件中的一个文本框保存,然后从文件保存到textbox1。我真的很感激这里的一些帮助。 提前谢谢。

    public MainPage()
    {
        this.InitializeComponent();
    }

    private void buttonsave_Click(object sender, RoutedEventArgs e)
    {
        string path = @"C:\Users\geora\Mytest.txt";
        if(!File.Exists(path))
        {
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine(textBox.Text);
            }
        }
    }

    private void buttonshow_Click(object sender, RoutedEventArgs e)
    {
        string path = @"C:\Users\geora\Mytest.txt";
        using (StreamReader sr = File.OpenText(path))
        {
            string s = "";
            s = sr.ReadLine();
            textBox1.Text = s;
        }
    }

2 个答案:

答案 0 :(得分:1)

您已打开文件但未关闭文件。这可能是问题

StreamReader sr = File.OpenText(path)

你需要关闭它。使用为您做到这一点(并将其配置为GC' d):

或者在.Net 2中,您可以使用新文件。静态成员,那么你不需要关闭任何东西:

variable = File.ReadAllText(path);

答案 1 :(得分:0)

除您的例外情况外 WPF版本:

private void loadButton_Click(object sender, RoutedEventArgs e)
{
  try
  {
    textBox.Text = File.ReadAllText(@"d:\test.txt");
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.ToString());
  }
}

private void saveButton_Click(object sender, RoutedEventArgs e)
{
  try
  {
    File.WriteAllText(@"d:\test.txt", textBox.Text);
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.ToString());
  }
}

UWP版本:

using System;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
...
private async void buttonSave_Click(object sender, RoutedEventArgs e)
{
  try
  {
    var storageFolder = ApplicationData.Current.LocalFolder;
    var sampleFile = await storageFolder.CreateFileAsync("sample.txt",
      CreationCollisionOption.ReplaceExisting);
    await FileIO.WriteTextAsync(sampleFile, textBox.Text);

    var msgbox = new MessageDialog(sampleFile.Path, "Your file is in");
    await msgbox.ShowAsync();
  }
  catch (Exception ex)
  {
    var msgbox = new MessageDialog(ex.ToString(), "Error");
    await msgbox.ShowAsync();
  }
}

private async void buttonLoad_Click(object sender, RoutedEventArgs e)
{
  try
  {
    var storageFolder = ApplicationData.Current.LocalFolder;
    var sampleFile = await storageFolder.GetFileAsync("sample.txt");
    textBox.Text = await FileIO.ReadTextAsync(sampleFile);
  }
  catch (Exception ex)
  {
    var msgbox = new MessageDialog(ex.ToString(), "Error");
    await msgbox.ShowAsync();
  }
}