创建和写入文件 [英] creating and writting file

查看:75
本文介绍了创建和写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string path = "C:\\mytest.txt";

if (File.Exists(path))
{
  File.Delete(path);
}
using (FileStream fs = File.Create(path))
{
  //fs.Close();
  // fs.CanWrite = true;
  TextWriter sw = new StreamWriter("C:\\mytest.txt");//error is coming here
  sw.WriteLine("ddd", "dddd", "dsdsd");
  --------------
  -------------
  --------
} 



我正在尝试创建文本文件并写入文本文件,但是正在给另一个人使用错误文件



I am trying to create and write to text file but is giving error file is being used by another person

推荐答案

这很自然,因为您试图两次打开文件:
的目的是什么
That''s natural since you''re trying to open the file two times: What''s the purpose of the
using (FileStream fs = File.Create(path))



是否再次打开文件(使用new StreamWriter("C:\\mytest.txt");)?

例如,请参见:"C#使用StreamWriter" [ ^ ].



if you then open again the file (with new StreamWriter("C:\\mytest.txt");)?

See, for instance: "C# Using StreamWriter"[^].


您遇到的问题是因为您刚刚使用以下行创建了文件:
The issue you are getting is because you''ve just created the file using the line:
using (FileStream fs = File.Create(path))

此时文件已打开,然后您尝试使用以下命令再次打开同一文件:

The file is open at this point, and you then attempt to open the same file again using:

TextWriter sw = new StreamWriter("C:\\mytest.txt");//error is coming here

使用其中一个.两者都不是.

Use one or the other. Not both.


这篇关于创建和写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆