繁体   English   中英

如何在Visual Studio中使用文件资源作为字符串?

[英]How do I consume a file resource as a string, in Visual Studio?

当我将txt文件作为资源添加到项目中时,如何将该资源的内容作为字符串使用?

我能够获得的最接近的结果是使用资源管理器来提取非托管流。 但是,这将引发空错误:

using (StreamReader sr = new StreamReader(
    Properties.Resources.ResourceManager.GetStream(
        "TestFile.txt", CultureInfo.CurrentCulture)))
{
    Console.WriteLine(sr.ReadToEnd());
}

您也可以这样做:

var myAss = Assembly.GetExecutingAssembly();
var mytxtFileResource = "Namespace.Project.MyTxtFile.txt";

using (Stream stream = assembly.GetManifestResourceStream(mytxtFileResource))
using (StreamReader reader = new StreamReader(stream))
{
    string result = reader.ReadToEnd();
}

您不需要对文本文件那样做,只需像这样https://msdn.microsoft.com/en-us/library/aa287548(v=vs.71).aspx

System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();

并像这样阅读: https : //msdn.microsoft.com/en-us/library/aa287535(v=vs.71).aspx

int counter = 0;
string line;

// Read the file and display it line by line.

System.IO.StreamReader file = 
   new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
   counter++;
}

file.Close();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM