【问题标题】:File reading and writing inside asp.net web application在 asp.net Web 应用程序中读取和写入文件
【发布时间】:2009-12-17 10:37:28
【问题描述】:

我在 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\

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

【问题讨论】:

  • 您知道如果您发现正确答案真的有用,您可以投票赞成吗? :)

标签: asp.net file web-applications file-io


【解决方案1】:

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

例子:

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

要使文件的路径成为本地文件,请使用以下命令

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

您的代码已修改

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

【讨论】:

    【解决方案2】:

    最好的办法是将文件添加到您的解决方案中。

    在解决方案探索中,您可以右键单击并添加现有项目。将您的代码更改为从该位置读取,因此当您部署代码时,它将位于已知位置并且是部署的一部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多