#c# #winforms #streamreader
#c# #winforms #streamreader
Вопрос:
Я хотел бы прочитать из текстового файла в Интернете определенное присвоение слову.
В выводе «содержимое» я получаю полное содержимое текстового файла.
Но я хочу только версию 7.7.3 из строки: version = «v7.7.3».
Как я могу выполнить фильтрацию по версии с помощью streamreader?
Это LastVersion.txt файл:
[general]
version = "v7.7.3"
messagenew = "Works with June 2018 Update!n Plus new Smart Farm strategyn New Siege Machinesn For more information, go to n https://mybot.run n Always free and open source."
messageold = "A new version of MyBot (v7.7.3) is available!nPlease download the latest from:nhttps://mybot.run"
Обновлено: это мой текущий код.
public string myBotNewVersionURL = "https://raw.githubusercontent.com/MyBotRun/MyBot/master/LastVersion.txt";
public string myBotDownloadURL = null;
public string userDownloadFolder = @"C:UsersXXXDownload";
public string newMyBotVersion = null;
public string currentMyBotVersion = null;
public string currentMyBotFileName = null;
public string currentMyBotPath = null;
public void Btn_checkUpdate_Click(object sender, EventArgs e)
{
OpenFileDialog openCurrentMyBot = new OpenFileDialog();
openCurrentMyBot.Title = "Choose MyBot.run.exe";
openCurrentMyBot.Filter = "Application file|*.exe";
openCurrentMyBot.InitialDirectory = userDownloadFolder;
if (openCurrentMyBot.ShowDialog() == DialogResult.OK)
{
MyBot_set.SetValue("mybot_path", Path.GetDirectoryName(openCurrentMyBot.FileName));
MyBot_set.SetValue("mybot_exe", Path.GetFullPath(openCurrentMyBot.FileName));
string latestMyBotPath = Path.GetFullPath(openCurrentMyBot.FileName);
var latestMyBotVersionInfo = FileVersionInfo.GetVersionInfo(latestMyBotPath);
currentMyBotVersion = "v" latestMyBotVersionInfo.FileVersion;
MyBot_set.SetValue("mybot_version", currentMyBotVersion);
WebClient myBotNewVersionClient = new WebClient();
Stream stream = myBotNewVersionClient.OpenRead(myBotNewVersionURL);
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
var sb = new StringBuilder(content.Length);
foreach (char i in content)
{
if (i == 'n')
{
sb.Append(Environment.NewLine);
}
else if (i != 'r' amp;amp; i != 't')
sb.Append(i);
}
content = sb.ToString();
var vals = content.Split(
new[] { Environment.NewLine },
StringSplitOptions.None
)
.SkipWhile(line => !line.StartsWith("[general]"))
.Skip(1)
.Take(1)
.Select(line => new
{
Key = line.Substring(0, line.IndexOf('=')),
Value = line.Substring(line.IndexOf('=') 1).Replace(""", "").Replace(" ", "")
});
newMyBotVersion = vals.FirstOrDefault().Value;
}
Комментарии:
1. Вы используете ужасный формат файла INI. Просто загуглите «анализатор файлов c # ini», чтобы найти код, но обязательно пропустите все, что использует GetPrivateProfileString().
2. Вы управляете форматом файла данных? Если это так, используйте JSON, он имеет гораздо лучшую поддержку для синтаксического анализа.
Ответ №1:
Чтение из локального
var vals = File.ReadLines("..\..\test.ini")
.SkipWhile(line => !line.StartsWith("[general]"))
.Skip(1)
.Take(1)
.Select(line => new
{
Key = line.Substring(0, line.IndexOf('=')),
Value = line.Substring(line.IndexOf('=') 1)
});
Console.WriteLine("Key : " vals.FirstOrDefault().Key
" Value : " vals.FirstOrDefault().Value);
Обновлено
для чтения из Git File.ReadLines не работает с URL.
string myBotNewVersionURL = "https://raw.githubusercontent.com/MyBotRun/MyBot/master/LastVersion.txt";
WebClient myBotNewVersionClient = new WebClient();
Stream stream = myBotNewVersionClient.OpenRead(myBotNewVersionURL);
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
var sb = new StringBuilder(content.Length);
foreach (char i in content)
{
if (i == 'n')
{
sb.Append(Environment.NewLine);
}
else if (i != 'r' amp;amp; i != 't')
sb.Append(i);
}
content = sb.ToString();
var vals = content.Split(
new[] { Environment.NewLine },
StringSplitOptions.None
)
.SkipWhile(line => !line.StartsWith("[general]"))
.Skip(1)
.Take(1)
.Select(line => new
{
Key = line.Substring(0, line.IndexOf('=')),
Value = line.Substring(line.IndexOf('=') 1)
});
Console.WriteLine("Key : " vals.FirstOrDefault().Key " Value : " vals.FirstOrDefault().Value);