Чтение определенного значения из текстового файла GitHub - PullRequest
0 голосов
/ 25 марта 2019

Я бы хотел прочитать из текстового файла в интернете определенное присвоение слову.

В выводе «content» я получаю полное содержимое текстового файла.

Но я хочу только v7.7.3 из строки: version = "v7.7.3" .

Как мне выполнить фильтрацию по версии с помощью ридера?

Это файл LastVersion.txt:

[general]
version    = "v7.7.3"
messagenew = "Works with June 2018 Update!\n Plus new Smart Farm strategy\n New Siege Machines\n 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:\Users\XXX\Download\";
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' && 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 Ответ

0 голосов
/ 25 марта 2019

Чтение из локального

  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' && 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...