-2

私は C# で最初のアプリケーションを開発しようとしていますが、単にファイルから読み書きしようとしています。私は何時間もの調査を行い、メンターに教えてもらいましたが、それは私には意味がありません.

フォームの先頭がレイアウトされており、使用している StreamWriter の正しい構文であると思われるものがありますが、ファイル名が別のプロセスで使用されているようで、どれかわかりません。ここに私が取り組んでいるコードがあります:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CustomerApplication
{
    public partial class AddCustomerForm : Form
    {
        public AddCustomerForm()
        {
            InitializeComponent();
        }
    private void saveAndExitBtn_Click(object sender, EventArgs e)

    {
        StreamWriter sw = File.AppendText("test.csv");


           sw.WriteLine("Test for Hope");

        // next, retrieve hidden form's memory address
        Form myParentForm = CustomerAppStart.getParentForm();
        // now that we have the address use it to display the parent Form
        myParentForm.Show();
        // Finally close this form
        this.Close();
    }// end saveAndExitBtn_Click method

これは、Visual Studio が気に入らない行です。

StreamWriter sw = File.AppendText("test.csv");

お時間をいただきありがとうございます。

~TT

4

2 に答える 2

2

ここでの推測に基づいています (ただし、ファイル名は別のプロセスで使用されているようです) - 書き込み用にファイルを開きますが、ファイルを閉じることはありません。そのため、後でもう一度書き込もうとすると失敗します。

これは、他のアプリケーション (メモ帳など) でファイルを開いている場合にも発生する可能性があることに注意してください。

ストリームの作成をusingステートメントに配置して、作業が終了したときにストリームが確実に閉じられるようにする必要があります。

using(StreamWriter sw = File.AppendText("test.csv")
{
    sw.WriteLine("Test for Hope");

    ...
}
于 2012-12-07T20:53:57.840 に答える
0

Are you sure you are not holding open the file somewhere else? For example before you step into that line of code you can try and delete the file manually to see if some process is holding onto it. I typed it in and it worked. I would recommend wrapping the Streamwriter in a using statement though and using the FileInfo object. The FileInfo object has a few nice properties on it like you can test to see if the file exists. You can do something like this also.

FileInfo fi = new FileInfo("C:\\test.csv");

if (fi.Exists)
  using (Streamwriter sw = fi.AppendText())
  {
     sw.WriteLine("tst");

     sw.Close();
  }
于 2012-12-07T20:56:03.987 に答える