创作与写作 [英] Creating and writing

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

问题描述

亲爱的朋友

我正在像这样在.txt文件上创建

Dear friends

I am creating on .txt file like this

FileStream fileStream = new FileStream(@"C:\mayur.txt", FileMode.Create);


文件已创建

在下一行中,我正在尝试初始化一个作家


file is created

on next line i am trying to initialise one writer

TextWriter sw = new StreamWriter(@"C:\\mayur.txt");


但它给出错误文件,这条线上的另一个人正在使用该文件

当我手动创建文件时,此代码可以正常工作,但是我没有在代码中创建文件


but it is giving error file is being used by another person on this line

when I create file manually and then this code works fine but this i am not creating file in code

How to solve this problem?

推荐答案

看看MSDN页面上的
Take a look at the MSDN page for FileStream[^]. It has a good example of how to create and write to a text file using this class.

Good luck!


您不应两次打开同一个文件.默认情况下,您有充分的理由使用独占访问权打开它们.如果您具有这样的双重访问权限,那将是非常危险的.在某些情况下,您无需在同一程序中将其打开两次.如果您仍然想要它,那就别再想要它了-它会解决您的问题.

仅使用StreamWriter;您不需要较低级别的流,但是可以在需要时获取基础流. 只需使用StreamWriter.BaseStream属性. [END EDIT]

如果仍然看不到如何仅用一个流编写器解决问题,请说明您要实现的目标.

—SA
You should not open the same file twice. By default, you open them with exclusive access, for a good reason. It would be really dangerous if you could have such dual access. There is not situations when you need to open it twice in the same program. If you still want it, stop wanting it — it will solve your problem.

Use just the StreamWriter; you don''t need lower-level stream, but you can get underlying stream when you need it. Just use StreamWriter.BaseStream property. [END EDIT]

If you still don''t see how to solve your problem with just one stream writer, please explain what do you want to achieve.

—SA


您两次打开相同的文件.打开/创建后,您将获得可用于作家的流.

试试这个:

You are opening the same file twice. After openening/creating you have a stream which you can use for your writer.

Try this:

FileStream fs = new FileStream(@"C:\TestFile.txt", FileMode.Create);
TextWriter tw = new StreamWriter(fs);
            
tw.WriteLine("Test");
            
tw.Close();
fs.Close();


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

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