2009-12-17 38 views
3

我已經開發了在Visual Studio中的ASP.NET Web應用程序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文件\微軟的Visual Studio 9.0 \ Common7 \ IDE \

我怎樣才能在應用程序中部署這兩個文件,以便該程序可以在另一個系統上工作?

+0

請給我看看這樣的代碼 – 2009-12-17 10:46:49

+0

如果你發現它們真的有用,你知道你可以upvote正確的答案嗎? :) – 2009-12-21 09:00:31

回答

9

最好的選擇是Server.MapPath()。

例子:

把裏面的文件夾「文件」(你可以做一個文件夾在您的解決方案,通過右鍵單擊您的解決方案,並選擇添加文件夾).. 然後右擊現有的folder..choose項目,然後選擇您的文件..

爲了使路徑文件的本地..使用遵循

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

你的代碼修改

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

最好的辦法是將文件添加到您的解決方案。

在解決方案勘誤中,您可以右鍵單擊並添加現有項目。將代碼更改爲從該位置讀取,因此當您部署代碼時,它將位於已知位置並且是部署的一部分。

相關問題