-1

我想问一下如何使用二进制格式化程序创建和编写文本文件我已经编写了以下代码,但我有一个例外。例外是:文件无法访问,因为它已被另一个进程使用。

我的代码创建了两个文件,一个带有扩展名“.txt”,另一个没有任何扩展名。

我该怎么办?还有另一种创建文本文件的方法吗?

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;


namespace ConsoleApplication9
{
    [Serializable]
    class contact
    {



        string name;
        string address;
        string phonenumber;
        string emailaddress;
        public override string ToString()
        {
            return name + "   " + address + "   " + phonenumber + "  " + emailaddress;
        }

        public void AddContent(string cname, string caddress, string cphone, string cemail)
        {
            name = cname;
            address = caddress;
            phonenumber = cphone;
            emailaddress = cemail;

            FileStream file = new FileStream("contact.txt", FileMode.OpenOrCreate, FileAccess.Write);

            BinaryFormatter bin = new BinaryFormatter();
            contact person = new contact();
            person.name = cname;
            person.address = caddress;
            person.phonenumber = cphone;
            person.emailaddress = cemail;
            bin.Serialize(file, person);
            file.Close();

            Console.WriteLine(" added sucefully");


        }//end of fun add

}

4

2 回答 2

2

您的异常与 BinaryFormatter 无关,而是与您没有正确处理 FileStream 的事实有关。始终将流包装在 using 块中:

 using(FileStream file = new FileStream("contact.txt", FileMode.OpenOrCreate, FileAccess.Write))
 {
    //code here
 }

这保证了下面的流被关闭并且非托管资源被释放。特别是在您的情况下,操作系统似乎仍然锁定您尝试创建的文件,并且第二次运行代码时会引发有关您的文件的异常being used by another process

于 2013-08-05T18:41:39.343 回答
0
 file can not been access because it is has been used by another process.

您是否有可能无意中打开了这个文件并且它仍然在文本窗口中打开?

于 2013-08-05T18:40:18.973 回答