說起這個,還真是費了一般功夫。
說個最簡單的方法:
第一步:把需要生成到Debug中的文件放到項目中(注意:當前文件夾目錄是什么樣的,存放到Debug中也是什么樣)
第二部:設置文件屬性中
復制到輸出目錄(如果較新則復制:就是在內容更改后就更新,不復制:不會復制,始終復制:如果該文件需要修改,不建議選擇此項)
生成操作(無,編譯,內容,嵌入的資源)
第三步:已經完成了,是不是很簡單。
還有個手動的方法(哈哈,有點麻煩哦!!!):
/// <summary> /// 項目中資源文件保存到Debug /// </summary> /// <param name="name">保存的文件名稱。比如:"文本.txt"</param> /// <param name="path">項目下的路徑。比如:".Demo.文本.txt"</param> /// <returns>0:保存失敗,1:保存成功,2:文件已存在</returns> public int FileSaveDebug(string name, string path) { string strStartupPath = System.Windows.Forms.Application.StartupPath; //Debug路徑 string pathsave = strStartupPath + "\\" + name; //項目名稱 if (!File.Exists(pathsave)) { try { string projectName = this.GetType().Assembly.GetName().Name; //項目名稱 Stream stream = this.GetType().Assembly.GetManifestResourceStream(projectName + path); using (FileStream fileStream = File.Create(pathsave)) { const int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int len; do { len = stream.Read(buffer, 0, bufferSize); fileStream.Write(buffer, 0, len); } while (len == bufferSize); } return 1; } catch (Exception ex) { return 0; } } else { return 2; } }
獲取項目文件內容(注意:文件屬性->生成操作(必須是:嵌入的資源)):
string content = ""; //內容
Stream stream = this.GetType().Assembly.GetManifestResourceStream(this.GetType().Assembly.GetName().Name + ".Demo.文本.txt"); if (stream == null) { System.Windows.Forms.MessageBox.Show("讀取文本失敗", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("GB2312"))) { content = reader.ReadToEnd().ToString(); }