[英]Visual Studio 2012 - C#: Reading a '.txt' File From Resources
我試圖從Visual Studio中的資源訪問和讀取文本文件'achInfo.txt'。 這個網站上已經列出了一些解決方法,但它們似乎都不適用於我。 他們只給我兩個錯誤中的一個,我將在后面解釋。
到目前為止,這是整個方法。
private string[] GetAchMetadata(short element)
{
string[] temp = { "", "" };
string cLine;
try
{
StreamReader sr = new StreamReader(Properties.Resources.achInfo);
while (!sr.EndOfStream)
{
cLine = sr.ReadLine();
if (Microsoft.VisualBasic.Information.IsNumeric(cLine))
{
if (int.Parse(cLine) == element)
{
temp[0] = cLine;
temp[1] = sr.ReadLine();
return temp;
}
}
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("There was a problem in collecting data.");
System.Diagnostics.Debug.Write(e);
}
return temp;
}
我的第一個假設是使用Properties.Resources.achInfo
,因為它直接引用了相關文件。 但是,這會引發System.ArgumentException
錯誤,其描述為“路徑中的非法字符”。
然后我使用了匯編解決方案('Grandma_Lair'是我的命名空間,不要問。'):
Assembly asm;
asm = Assembly.GetExecutingAssembly();
StreamReader sr = new StreamReader(asm.GetManifestResourceStream("Grandma_Lair.achInfo.txt"));
但是,這會拋出一個System.ArgumentNullException
,並顯示消息“Value not not null”。 我還將我的資源上的訪問修飾符設置為public,並確保將該文件設置為Embedded Resource。
有沒有人對我的問題有任何想法?
使用StringReader
替換StreamReader
,您的第一個解決方案應該可以正常工作:
StringReader sr = new StringReader(Properties.Resources.achInfo);
值Properties.Resources.achInfo
表示您作為字符串給予的整體嵌入的資源,而不是該資源的路徑(因此“路徑中的無效字符”錯誤)。
GetManifestResourceStream
方法也應該工作,但是您需要為方法提供正確的路徑,該路徑除了其他之外,還基於項目的默認命名空間的名稱。 如果在嘗試獲取資源之前添加對assembly.GetManifestResourceNames()
的調用,並在調試器中查找資源名稱的確切拼寫,則應該能夠修復空指針異常問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.