如何创建.txt文件并将其编写为c#asp.net [英] how to create .txt file and write it c# asp.net

查看:97
本文介绍了如何创建.txt文件并将其编写为c#asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码在C#应用程序中创建并写入文本文件

I am trying create and write to a text file in a C# application using the following code

System.IO.Directory.CreateDirectory(Server.MapPath("~\\count"));

using (System.IO.FileStream fs = new System.IO.FileStream("~/count/count.txt", System.IO.FileMode.Create))
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("~/count/count.txt"))
{
    sw.Write("101");
}

string _count = System.IO.File.ReadAllText("~/count/count.txt");
Application["NoOfVisitors"] = _count;

但是我得到一个错误:

该进程无法访问文件'path',因为它正在被另一个进程使用.

The process cannot access the file 'path' because it is being used by another process.

我的错误是什么?

推荐答案

您正在尝试打开文件两次;您的第一个 using 语句会创建一个未使用的 FileStream ,但会锁定文件,因此第二个 using 会失败.

You're trying to open the file twice; your first using statements creates a FileStream that is not used, but locks the file, so the second using fails.

只需删除您的第一行 行,一切都可以正常工作.

Just delete your first using line, and it should all work fine.

但是,我建议将所有内容替换为 File.WriteAllText ,这样您的代码中就不会再使用了,它会简单得多.

However, I'd recommend replacing all of that with File.WriteAllText, then there would be no using in your code, it'd be much simpler.

var dir = Server.MapPath("~\\count");
var file = Path.Combine(dir, "count.txt");

Directory.CreateDirectory(dir);
File.WriteAllText(file, "101");

var _count = File.ReadAllText(file);
Application["NoOfVisitors"] = _count;

这篇关于如何创建.txt文件并将其编写为c#asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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