Search code examples
c#seleniumselenium-webdriverwebdriverfilestream

Can I use a variable to set a path in FileStream?


I have a test script in Selenium Webdriver using C# in which I read data from a .txt external file.

The path is fixed on the script, indicating a folder on my computer. But in the future other people will run this script in other computers and they will have to adjust the path manually directly on the script.

Is it possible to set the path C:\Users\...\myData.txt like a kind of a variable, I mean, not being permanent on the body of the script?

This is the part of the script:

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();
                }
            }
        }

Solution

  • Question solved by making the relative path, same, adding my .txt from each project in Solution Explorer, in the respective csprojs.

    Imagining that the solution is the root and placed my .txt in the same relative path used in the new FileStream (path).

    In Solution Explorer, right-clicked the .txt and went to Properties. Under Copy To Output Directory > Copy if newer.

    @Kaj & @papparazzo, I'd be glad if you took off the negative votes of this question, if you want.