好的,所以我有一個html文檔,我參考我的Visual Studio 2010 C#應用程序,我需要爲應用程序繼續。如何在我的C#項目中包含文檔?
這裏來代碼
string template = System.IO.File.ReadAllText("template.html");
的template.html
文件是當前在我的調試目錄,我希望能夠把它列入如果可能的exe文件,因此用戶不必擁有的副本HTML文件爲我的應用程序運行...有關如何解決此問題的任何想法
好的,所以我有一個html文檔,我參考我的Visual Studio 2010 C#應用程序,我需要爲應用程序繼續。如何在我的C#項目中包含文檔?
這裏來代碼
string template = System.IO.File.ReadAllText("template.html");
的template.html
文件是當前在我的調試目錄,我希望能夠把它列入如果可能的exe文件,因此用戶不必擁有的副本HTML文件爲我的應用程序運行...有關如何解決此問題的任何想法
您必須右鍵單擊該文件並使其成爲嵌入式資源。
然後你可以用下面的代碼訪問您的文件:
using (Stream stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("template.html"))
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
}
更多信息在:http://msdn.microsoft.com/en-us/library/xc4235zt(v=vs.100).aspx
所以這wont再工作string template = System.IO.File.ReadAllText(「template.html」); – Trace 2012-03-22 14:46:02
不可以,因爲文件在物理位置上不存在 - 它將在編譯時嵌入到程序集中 – 2012-03-22 14:48:11
右鍵單擊解決方案資源管理器中的HTML文件 - >屬性 - >設置內容類型爲Embedded Resource。
更新: 您可以通過訪問{} ProjectBaseNameSpace {.Properties.Resources}資源名稱
包含在項目中的文件,並生成操作
下設置「嵌入的資源」,然後就可以訪問該資源,這裏是如何的例子:
Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
string resourcePath = ".Templates.ActivationEmailTemplate.html";
Stream stream = asm.GetManifestResourceStream(asm.GetName().Name + resourcePath);
注意到,我的ActivationEmailTemplate.html是在「模板」文件夾中
難道他們必須能夠將其視爲物理文件還是可以將其嵌入到exe中? – BugFinder 2012-03-22 14:39:25
http://blogs.msdn.com/b/alexdan/archive/2007/12/19/loading-embedded-resources-in-c-using-getmanifestresourcestream.aspx – ken2k 2012-03-22 14:40:22
你也可以把它放在你的項目中,讓它內容,始終複製。這將始終將其放在輸出目錄中。 – user7116 2012-03-22 14:51:58