tib*_*hew 3 asp.net file-io web-applications file
我在Visual Studio 2008中开发了一个ASP.NET Web应用程序.
我在应用程序中有一个HTML文档和一个文本文件,但两者都不在我的应用程序中.
两者都在外面,所以当我尝试在另一个系统中运行相同的应用程序时,我收到错误,因为我错过了那些文件.
我想在部署时将文件包含在应用程序中.
下面是我用来读写文件的代码:
//file write test.txt
FileStream file1 = new FileStream("test.txt", FileMode.Create, FileAccess.Write);
// Create a new stream to write to the file
StreamWriter sw1 = new StreamWriter(file1);
// Write a string to the file
sw1.Write(emailId);
// Close StreamWriter
sw1.Close();
// Close file
file1.Close();
// *** Write to file ***
// Specify file, instructions, and privelegdes
FileStream file = new FileStream("test.html", FileMode.Create, FileAccess.Write);
// Create a new stream to write to the file
StreamWriter sw = new StreamWriter(file);
// Write a string to the file
sw.Write(BodyLiteral.Text);
// Close StreamWriter
sw.Close();
// Close file
file.Close();
// *** Read from file ***
// Specify file, instructions, and privelegdes
file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Read);
// Create a new stream to read from a file
StreamReader sr = new StreamReader(file);
// Read contents of file into a string
string cval = sr.ReadToEnd();
Response.Write(cval);
// Close StreamReader
sr.Close();
// Close file
file.Close();
//html file reading
string text = File.ReadAllText(@"D:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\test.html");
Run Code Online (Sandbox Code Playgroud)
我的两个文件都在:D:\ Program Files\Microsoft Visual Studio 9.0\Common7\IDE \
如何将这两个文件与应用程序一起部署,以便程序可以在另一个系统上运行?
你最好的选择是Server.MapPath().
例:
将文件放在文件夹"文件"中(您可以在解决方案中创建一个文件夹,通过右键单击您的解决方案并选择添加文件夹)..然后右键单击文件夹.选择现有项目,然后选择您的文件..
要使文件的路径为本地..请使用以下内容
Server.MapPath("~\\files\\test.html");
Run Code Online (Sandbox Code Playgroud)
您的代码已修改
FileStream file = new FileStream( Server.MapPath("~\\files\\test.html"), FileMode.Create, FileAccess.Write);
Run Code Online (Sandbox Code Playgroud)