我对C#代码
有疑问如何从文本文件中读取此代码?
#Msg 10001
{
This is message
}
我想阅读ID为10001的文本,并阅读{}
中写的消息答案 0 :(得分:2)
你应该阅读带有消息的文本文件,然后解析它
// Reading the file
String text = File.ReadAllText(@"MyMessageFile.txt");
// Parsing: startIndex - index of the first '{' from the heading
// that is #Msg ... 10001
int startIndex = text.IndexOf('{', Regex.Match(text, @"#Msg\ *10001").Index);
// stop index: closing '}'
int stopIndex = text.IndexOf('}', startIndex);
// Message is text between '{' and '}'
// heading and trailing whitespaces (\n, \n, ' ') removed
String message = text.Substring(startIndex + 1, stopIndex - startIndex - 1).Trim(' ', '\r', '\n');
答案 1 :(得分:1)
如果你想要一个例子,我会给你这个:
using System.IO;
您必须将其添加到。^
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
Console.ReadLine();
sr.Close();
注意:文件必须位于项目的Debug文件夹中,否则您必须复制并粘贴文件路径。
此外,请不要在本网站上提出含糊的问题,否则您可能无法得到答案。欢迎来到这个站点btw。