簡體   English   中英

從C#Resources讀取文本文件

[英]Read text file from C# Resources

我需要從我的資源中讀取一個文件並將其添加到列表中。 我的代碼:

private void Form1_Load(object sender, EventArgs e)
{
    using (StreamReader r = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("myProg.myText.txt")))
    {
        //The Only Options Here Are BaseStream & CurrentEncoding
    }
}

我搜索了這個,只得到了像"Assembly.GetExecutingAssembly...."這樣的答案,但我的程序沒有選擇匯編。

嘗試這樣的事情:

string resource_data = Properties.Resources.test;
List<string> words = resource_data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).ToList();

哪里

在此輸入圖像描述

您需要using System.Reflection;包含using System.Reflection; 在您的標題中,以便訪問Assembly。 這僅適用於在VS中將文件標記為“嵌入式資源”的情況。

var filename = "MyFile.txt"
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNameSpace." + filename));

只要你包含'using System.Reflection;' 您可以像這樣訪問Assembly:

Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace." + filename);

或者如果您不需要改變文件名,只需使用:

Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace.MyFile.txt");

完整代碼應如下所示:

using(var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("myProg.m‌​yText.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // Do some stuff here with your textfile
    }
}

接下來,AppDeveloper解決方案即將推出。

string resource_data = Properties.Resources.test;
string [] words = resource_data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
foreach(string lines in words){
.....
}
        [TestCategory("THISISATEST")] 
        public void TestResourcesReacheability() 
        { 
            byte[] x = NAMESPACE.Properties.Resources.ExcelTestFile; 
            string fileTempLocation = Path.GetTempPath() + "temp.xls"; 
            System.IO.File.WriteAllBytes(fileTempLocation, x);   

            File.Copy(fileTempLocation, "D:\\new.xls"); 
        }

您將資源文件作為字節數組獲取,因此您可以使用WriteAllBytes創建新文件。 如果您不知道在哪里可以編寫文件(權限和訪問的原因),您可以使用Path.GetTempPath()來使用PC臨時文件夾來編寫新文件,然后您可以從那里復制或工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM