【问题标题】:Find and replace the data in text file using selenium C#使用 selenium C# 查找和替换文本文件中的数据
【发布时间】:2016-05-04 09:16:48
【问题描述】:

我有一个要上传到 UI 中的文本文件。每次测试运行前都需要更新文本文件。我需要在我的 Selenium C# 脚本中捕获它。

以下是数据格式:

0                 01CBA       Sou                  301500PAYMEN72    080416                                        
1062-000 14138 130000000012ROSY                            DEBITFROM

080416 是日期。每次脚本运行时,我都需要将其替换为系统日期。

如何获取日期的位置并替换它。

【问题讨论】:

    标签: c# selenium


    【解决方案1】:

    我可以使用正则表达式来替换日期:

    // load the file
    string text = File.ReadAllText(@"C:\yourfile.txt");
    
    // replace the date
    string text2 = Regex.Replace(text, @"\b080416\b", DateTime.Now.ToString("ddmmyy"));
    
    // save the updated text to a temp file
    string tempPath = string.Format("{0}myfile-{1:X}.txt", Path.GetTempPath(), DateTime.Now.Ticks);
    File.WriteAllText(tempPath, text2);
    
    // upload the file
    driver.FindElementByCssSelector("input[type=file]").SendKeys(tempPath);
    

    【讨论】:

    • 非常感谢您的解决方案。它可以更通用,因为 080416 不是恒定的。每次编辑和保存文件时它都会改变。但是字符串的位置会是一样的。
    • @SachuDev,你也可以使用这个正则表达式来匹配一个未知的日期:\b[0123]\d[01]\d1\d\b
    • 感谢 Florent B 的回答。
    • 我使用下面的代码解决了这个问题: var reader = new StreamReader(filepath); var str = reader.ReadToEnd(); reader.Close(); var 替换字符串 = str.Replace(str.Substring(74, 6), DateTime.Now.ToString("ddMMyy")); var writer = new StreamWriter(filepath); writer.Write(replacedString); writer.Close();
    猜你喜欢
    • 2022-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 2011-06-12
    • 2012-02-14
    • 1970-01-01
    • 2019-07-02
    • 2020-07-29
    相关资源
    最近更新 更多