C# 将文件写入 Web 服务器 - ASP.NET
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1268766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing file to web server - ASP.NET
提问by Woody
I simply want to write the contents of a TextBox control to a file in the root of the web server directory... how do I specify it?
我只是想将 TextBox 控件的内容写入 Web 服务器目录根目录中的文件...我该如何指定?
Bear in mind, I'm testing this locally... it keeps writing the file to my program files\visual studio\Common\IDE directory rather than my project directory (which is where I assume root is when the web server fires off).
请记住,我正在本地测试...它不断将文件写入我的程序 files\visual studio\Common\IDE 目录而不是我的项目目录(这是我假设 web 服务器启动时 root 所在的位置) .
Does my problem have something to do with specifying the right location in my web.config? I tried that and still no go...
我的问题是否与在 web.config 中指定正确的位置有关?我试过了,还是不行...
Thanks much...
非常感谢...
protected void TestSubmit_ServerClick(object sender, EventArgs e) { StreamWriter _testData = new StreamWriter("data.txt", true); _testData.WriteLine(TextBox1.Text); // Write the file. _testData.Close(); // Close the instance of StreamWriter. _testData.Dispose(); // Dispose from memory. }
采纳答案by Darthg8r
protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true))
{
_testData.WriteLine(TextBox1.Text); // Write the file.
}
}
Server.MapPath takes a virtual path and returns an absolute one. "~" is used to resolve to the application root.
Server.MapPath 采用一个虚拟路径并返回一个绝对路径。“~”用于解析到应用程序根。
回答by Sean Bright
protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
using (StreamWriter w = new StreamWriter(Server.MapPath("~/data.txt"), true))
{
w.WriteLine(TextBox1.Text); // Write the text
}
}
回答by Spencer Ruport
Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.
请记住,一旦您上传到您的 Web 服务器,您还必须授予 IUSR 帐户对该文件夹的写访问权限。
Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.
我个人建议不要允许对根文件夹进行写访问,除非您有充分的理由这样做。然后你需要小心你允许保存什么样的文件,这样你就不会无意中允许某人编写他们自己的 ASPX 页面。
回答by Guffa
There are methods like WriteAllText
in the File
class for common operations on files.
有喜欢的方法WriteAllText
在File
类文件上常见的操作。
Use the MapPath
method to get the physical path for a file in your web application.
使用该MapPath
方法获取 Web 应用程序中文件的物理路径。
File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);