如何在server.mappath中写入现有文件 [英] How do I write over an existing file in server.mappath

查看:63
本文介绍了如何在server.mappath中写入现有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用以下方法在Server.MapPath(file.xml)中写入现有文件:

Is it possible to write over an existing file in Server.MapPath(file.xml) using:

using (FileStream fsAppend = new FileStream(Server.MapPath("file1.xml"), FileMode.Append, FileAccess.Write))
{
   StreamWriter sw = new StreamWriter(fsAppend);
   ???
}



或者以某种方式使用FileMode.Truncate?然后FileMode.Create?



我尝试过:



FileMode 。如果我找出语法,似乎要走了。我根本不想尝试FileMode.Truncate。


Or somehow using FileMode.Truncate?? then FileMode.Create?

What I have tried:

FileMode.Append seems the way to go if I figure out the Syntax. I do not want to even try FileMode.Truncate at all.

推荐答案

FileMode.Append总是打开文件,如果它存在,则将写入位置设置为流。因此它永远不会替换现有文件,它只是添加它。

FileMode.Create是你想要的文件:它替换现有文件(如果存在),或创建一个新文件,如果它没有' t。



但......这是一个很大的但是......小心使用试试......抓住阻止您的代码:网站本质上是多用户,并且涉及写入的标准FileIO操作总是锁定文件以进行独占访问。如果该文件被其他网站用户使用,则您的代码将失败。
FileMode.Append always opens the file and if it exists, sets the write position to the end of the stream. So it will never replace the existing file, it just adds to it.
FileMode.Create is the one you want: it replaces an existing file if one exists, or creates a new file if it doesn't.

But ... and it's a big "but ... be careful to use a try...catch block with your code: websites are intrinsically multiuser, and standard FileIO operations which involve writing always lock the file for exclusive access. If the file is in use by another website user, your code will fail.


这篇关于如何在server.mappath中写入现有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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