读书人

新人有关问题:创建和写文件

发布时间: 2012-03-30 17:32:09 作者: rapoo

新人问题:创建和写文件
部分代码如下:[code=C#][/code]namespace myFile2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnCreate_Click(object sender, EventArgs e)
{
if (!File.Exists(@"E:\My File.dat"))
{
File.CreateText(@"E:\My File.dat");
}
}
private void btnWrite_Click(object sender, EventArgs e)
{
try
{
using (StreamWriter sw =(@"E:\My File.dat"))
{
sw.WriteLine("It is just a test");
sw.Close();
sw.Dispose();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

点击第一个按钮创建文件,接着点第二个按钮向文件写入一些内容。为什么会出现异常,说文件正在被另一个进程使用。
弄了一个小时也没有解决,发帖问问
另:因为创建文件和写入不是同时进行的,该怎么办
不要笑话我的问题低级啊


[解决办法]

C# code
 private void btnCreate_Click(object sender, EventArgs e)        {            FileStream fs = new FileStream(@"E:\My File.dat", FileMode.OpenOrCreate);            fs.Dispose();            fs.Close();                    }        private void btnWrite_Click(object sender, EventArgs e)        {            try            {                FileStream fs = new FileStream(@"E:\My File.dat", FileMode.Open);                StreamWriter sw = new StreamWriter(fs);                sw.WriteLine("It is just a test");                sw.Flush();                sw.Close();                fs.Close();                fs.Dispose();            }            catch (Exception ex)            {                MessageBox.Show(ex.Message);            }        }
[解决办法]
C# code
 private void btnCreate_Click(object sender, EventArgs e)  {  if (!File.Exists(@"E:\My File.dat"))  {  File.CreateText(@"E:\My File.dat").Close();//此处释放数据流对文件的操作才会在下次BUTTON事件中写操作中不会被其他进程占有。  }  } 

读书人网 >C#

热点推荐