gpt4 book ai didi

asp.net - ASP.NET Web 应用程序中的文件读写

转载 作者:行者123 更新时间:2023-12-02 17:52:14 25 4
gpt4 key购买 nike

我在 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");

我的两个文件都位于:D:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\

如何将这两个文件与应用程序一起部署,以便该程序可以在另一个系统上运行?

最佳答案

你最好的选择是 Server.MapPath()。

示例:

将文件放入文件夹"file"中(您可以在解决方案中创建一个文件夹,方法是右键单击您的解决方案并选择添加文件夹)。然后右键单击该文件夹..选择现有项目,然后选择您的文件..

要将文件路径设置为本地..请使用以下内容

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

您的代码已修改

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

关于asp.net - ASP.NET Web 应用程序中的文件读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1920833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com