使用Stream Writer从文本框写入文本文件 [英] Writing to textfile from textbox using Stream Writer

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

问题描述

我使用以下代码写入文件。 filename是包含文件路径的字符串。当我第一次写入文本框并保存时,它会被保存到文件中,但是当我转到其他页面并再次返回同一页面,然后再次尝试做同样的事情时,它是没有保存到文件。

出现的错误是

进程无法访问文件'c:\ blahblah',因为它正由另一个进程使用。





 使用(StreamWriter sw =  new  StreamWriter(filename))
{
// 写入文件
sw.Write(TextBox1.Text);

}







我尝试了很多解决方案。许多地方据说使用操作员正确关闭文件。



需要紧急帮助。

解决方案

< blockquote>你说的是页面,还有C:\ blahblah - 两者不兼容。

页面意味着我们这里有一个基于我们的解决方案,但如果你是运行一个网站,然后你通常无法直接访问C:驱动器 - 如果有的话 - 因为它是由许多网站共享的,你应该使用相对于你的网站根文件夹的路径。

此外,出于安全原因,任何引导设备的根目录都很难写入 - 尝试时通常会出现访问冲突错误。



因此,我认为您没有对此进行过充分的解释:所以从调试器开始,看看到底发生了什么。在上面的代码的Write行中放置一个断点,并确保在执行代码时它被命中。仔细查看文件名并检查它是否与您的想法完全一致。然后继续该程序,看看当你再次尝试做同样的事情会发生什么。



我怀疑你有不同的代码也访问不在的文件使用块。


I am using the following code to write to a file. filename is a string containing the path of the file. When I first time write to the text box and save it, it is getting saved to the file, but when I go to some other page and come back to the same page again, and then again try to do the same thing, it is not getting saved to the file.
The error which comes is
The process cannot access the file 'c:\blahblah' because it is being used by another process.


using (StreamWriter sw = new StreamWriter(filename))
{
    //write to the file
    sw.Write(TextBox1.Text);

}




I have tried many solutions. Many places it is said that "using" operator closes the file properly.

Urgent help required.

解决方案

You are talking about "pages" and also about "C:\blahblah" - and the two are not compatible.
"Pages" imply a we-based solution here, but if you are running a website, then you normally can't access the C: drive directly - if at all - because it is shared by a number of sites and you should be using a path relative to your website root folder.
In addition, the root directory of any boot device is difficult to write to for security reasons - you would normally get an "access violation" error when trying.

So I don't think you have quite explained this properly: so start with the debugger and see what exactly happens. Put a breakpoint on the Write line of your code above, and make sure it is hit when the code is executed. Look at the filename closely and check it is exactly what you think it is. Then continue the program and see what happens when you try and do the same thing again.

I suspect you have different code also accessing the file which isn't in a using block.


这篇关于使用Stream Writer从文本框写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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