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

Can I use a variable to set a path in 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();
                }
            }
        }

你尝试了吗?它只是一个字符串。

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

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

static int Main(string[] args)

我可能有点误解你的问题,因为我是新来的。但是,如果您只是想要一个不是静态定义的并且可以由用户更改的路径变量;你可以使用 config file to define it and point to the config instead. (Or ConfigurationManager MSDN-ConfigManager)

有多种方法可以做到这一点。

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

  2. 我看到您正在使用 NUnit。 NUnit 有 TestContext.CurrentContext.TestDirectory 将 return 测试 dll 的路径。如果您将 txt 文件添加到您的解决方案中,并通过 post-build 事件将其与 dll 一起复制,它将始终位于 TestDirectory.

通过创建相对路径解决了问题,同样,在解决方案资源管理器中的每个项目中添加我的 .txt,在各自的 csprojs.

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

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

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