我可以使用变量在FileStream中设置路径吗?

时间:2018-06-22 17:31:53

标签: c# selenium selenium-webdriver webdriver filestream

我在Selenium Webdriver中使用C#编写了一个测试脚本,该脚本从.txt外部文件中读取数据。

路径在脚本上是固定的,表示我的计算机上的文件夹。但是将来其他人将在其他计算机上运行此脚本,他们将不得不直接在脚本上手动调整路径。

是否可以像设置某种变量那样设置路径C:\Users\...\myData.txt,而不是在脚本主体中永久存在?

这是脚本的一部分:

using System;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.IO;
using System.Collections;
using System.Text;

namespace SeleniumTests
{
    [TestFixture]
    public class Principal
    {
        IWebDriver driver = null;

        [SetUp]
        public void SetUp()
        {
            ChromeOptions options = new ChromeOptions();
            options.AddArguments("--disable-infobars");
            options.AddArguments("start-maximized");
            driver = new ChromeDriver(options);
        }

        public class DataTXT
        {
            public string example1{ get; set; }
            public string example2{ get; set; }
            public string example3{ get; set; }
            public string example4{ get; set; }
        }

        public static IEnumerable DataTXT
        {
            get
            {
                string linha;
                using (FileStream readFile =
                new FileStream(@"C:\Users\...\myData.txt", FileMode.Open, FileAccess.Read))
                {
                    var reader = new StreamReader(readFile, Encoding.GetEncoding("iso-8859-1"));

                    while ((line = reader.ReadLine()) != null)
                    {
                        var column = line.Split(';');
                        yield return new DataTXT
                        {
                            example1 = column[0],
                            example2 = column[1],
                            example3 = column[2],
                            example4 = column[3]
                        };
                    }
                    reader.Close();
                    readFile.Close();
                }
            }
        }

4 个答案:

答案 0 :(得分:0)

您尝试了吗?这只是一个字符串。

public string FilePath { get; set: }
using (FileStream readFile =
new FileStream(FilePath, FileMode.Open, FileAccess.Read))
{

您可以在命令行中传递数据

static int Main(string[] args)

答案 1 :(得分:0)

由于我在这里有点陌生,所以我可能会误解您的问题。但是,如果您只需要一个路径变量,该变量不是静态定义的,并且可以由用户更改;您可以使用config文件来定义它并指向配置。 (或ConfigurationManager MSDN-ConfigManager

答案 2 :(得分:0)

您可以通过多种方式进行此操作。

  1. 您可以在项目内部创建路径,并知道它相对于\ bin的位置。

  2. 我看到您正在使用NUnit。 NUnit具有TestContext.CurrentContext.TestDirectory,它将返回测试dll的路径。如果您将txt文件添加到解决方案中,并通过生成后事件将其复制到dll中,则它将始终位于TestDirectory中。

答案 3 :(得分:0)

通过使相对路径相同,并从解决方案资源管理器中的每个项目中将我的.txt添加到相应的csprojs中来解决问题。

假设解决方案是根,并将我的.txt放在新FileStream (path)中使用的相对路径中。

在解决方案资源管理器中,右键单击.txt,然后转到PropertiesUnder Copy To Output Directory > Copy if newer

@Kaj&@papparazzo,如果您愿意的话,如果您对这个问题投反对票,我会很高兴。