开发者

File reading and writing inside asp.net web application

开发者 https://www.devze.com 2022-12-14 11:18 出处:网络
I have developed an ASP.NET web application in Visual Studio 2008. I have an HTML document and one text file in the application, but both are not inside my application.

I have developed an ASP.NET web application in Visual Studio 2008.

I have an HTML document and one text file in the application, but both are not inside my application.

Both are outside, so when I try to run the same application in another system, I get an error because I am missing those files.

I want to include the files inside the application when I deploy it.

Below is the code I use to read and write the files:

//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");

Both of my files are in: D:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\

How can I deploy these two files with application so that the program will work on another system?


Your best bet would be Server.MapPath().

Example:

Put the files inside folder "file" (you can make a folder in your solution, by right clicking your solution and choose add folder).. then right click the folder..choose existing item , and then choose your files..

To make the path to your files local.. use the follow

Server.MapPath("~\\files\\test.html");

Your code modified

 FileStream file = new FileStream(  Server.MapPath("~\\files\\test.html"), FileMode.Create, FileAccess.Write);


Best thing to do is to add the files to your solution.

In solution exploere you can right-click and add an existing item. Change your code to read from that location, so when you deploy your code it will be in a known location and part of the deployment.

0

精彩评论

暂无评论...
验证码 换一张
取 消