Dynamic Paths for MStest Unit Test DataSource - c#

I am using CSV files as datasource for my MSTest unit tests. I had the idea that I would generate dynamic file paths for the CSV file, store them in a variable and then pass the variable in ConnectionString of databasesource for the unit tests.
However, now I have learned that we cannot pass variable in Datasource Connection string. Any idea how can I make the file path dynamic as the unit test dll will be executed on different machines and a static path is not an option.
The CSV files are already added in the solution.

public string GetAbsolutePath(string relativePath)
{
string path = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
int lastIndex = path.LastIndexOf("bin", StringComparison.OrdinalIgnoreCase);
string actualPath = path.Substring(0, lastIndex);
string projectPath = new Uri(actualPath).LocalPath;
string absolutePath = projectPath + relativePath;
return absolutePath;
}
The above code is for c# will run on any machine to reach file inside your project. this code will give your project folder path in "projectPath " variable even if you use different machines because it is generated with reference to your dll file. the only thing you need to do is pass relative path of folder or file you want to reach inside your project.
Note:- find bin folder in your project "projectPath" variable will give you path till that and then accordingly pass your relative path as a parameter. Please debug function to get a clear understanding.
Let me know if you need clarification

Related

How do i get a relative path of a file when running my code in debug for coded ui

I'm trying not to hard code my path, but I have not been able to figure our a way to get to an xml file that I have included in my project under a folder labeled Datasource. Here is my latest code that I have tried which still doesn't work.
public static string myAssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
string fileName = xmlFileName;
string path = Path.Combine(myAssemblyDirectory, #"DataSource\" + fileName);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
Here is the output for the path that I'm getting which is putting it in my test results output folder.
"C:\MyAutomation\Automated_Test_Projects\AutomationProjects\MiserReleaseTestSuites\TestResults\marcw_ISD2005M 2016-02-05 10_15_17\Out\DataSource\Miser_Login_Dts.xml"
If possible I'd like to point it to
"C:\MyAutomation\Automated_Test_Projects\AutomationProjects\MiserReleaseTestSuites\MiserReleaseTestSuites\DataSource\Miser_Login_DTs.xml"
".." Can be used to go to the relative parent directory. "." Refers to the current directory.
You can combine these to form a relative path that starts higher up in the directory tree.
In your example you need to go 3 directories higher than the out folder and then into the MiserReleaseTestSuites\DataSource folder. Combining this produces
#"..\..\..\MiserReleaseTestSuites\DataSource\"
You can deploy the file in the same manner as you would when data driving the tests. See https://stackoverflow.com/a/25742114/546871
The TestContext class contains several fields with "directory" in their names. These can be used to access the various directories associated with running the tests. See also https://stackoverflow.com/a/19682311/546871

Storing MSSQL LocalDB for Application

I have been using a LocalDB.mdf file to build my application, but now need to use it in production and create an installable application.
After research, it seems the best place to store such a file is in the /Appdata/Local/ folder.
I intend to create a new LocalDB.mdf file in there if it doesnt already exist, or has been deleted.
I have a pre-made LocalDB.mdf file in my App Resources, which I wanted to copy into this /Appdata/Local/ folder on first run, but I am seeing an Access is denied error.
I can create a blank file ok to that folder.
Here is the code:
string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string dvAppDataFolder = appDataFolder + #"\MyApp";
AppDomain.CurrentDomain.SetData("DataDirectory", dvAppDataFolder);
if (!Directory.Exists(dvAppDataFolder))
Directory.CreateDirectory(dvAppDataFolder);
if (!File.Exists(dvAppDataFolder + "LocalDB.mdf"))
{
File.WriteAllBytes(dvAppDataFolder, LokiServer.Properties.Resources.newDB);
}
In addition, Am I going about this the right way?
This line
if (!File.Exists(dvAppDataFolder + "LocalDB.mdf"))
is probably wrong. Missing the backslash, better to use Path.Combine instead of a string concatenation.
Finally, you want to write to a file not to a folder
string fileName = Path.Combine(dvAppDataFolder,"LocalDB.mdf");
if (!File.Exists(fileName))
{
File.WriteAllBytes(fileName, LokiServer.Properties.Resources.newDB);
}
Are you doing it right? It depends. If your app data should be kept separated for each user of your target machine then you are right, but if you want your database to be available to all users of that machine then use
string appDataFolder = Environment.GetFolderPath
(Environment.SpecialFolder.CommonApplicationData);

Folder path before project

I am trying to get a folder path in my C drive that I did not want to hard code with my program.
I know that I can use string path = System.AppDomain.CurrentDomain.BaseDirectory; However its give me : C:\FACE\Camera\Camera\bin\Debug . Which I want to only have C:\FACE\ as I want to initialise something in the FACE folder but outside of my Camera folder. I do not wish to hardcode the file path. Is it possible to do it? Thanks for the help!
You could use the method Directory.GetParent for this purpose:
Directory.GetParent("here you will pass you path");
Update
For your case, you could take that you want as below:
string projectPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string solutionPath = Directory.GetParent(projectPath).Parent.FullName;
string basePath = Directory.GetParent(solutionPath).FullName;
The variable basePath contains that you want.
System.AppDomain.CurrentDomain.BaseDirectory always returns the path of executable assembly.You can use DTE if you are using web application

Ways to get the relative path of a folder

I have one folder named "Images" in my project. I want to get the path of the Image folder so that I can browse that and get the files.
I'm using below piece of code for my above requirement and it is working fine.
string basePath = AppDomain.CurrentDomain.BaseDirectory;
basePath = basePath.Replace("bin", "#");
string[] str = basePath.Split('#');
basePath = str[0];
string path = string.Format(#"{0}{1}", basePath, "Images");
string[] fileEntries = Directory.GetFiles(path);
foreach (string fileName in fileEntries)
listBox.Items.Add(fileName);
Just want to know like is there any elegant way of doing this? What are the best ways of getting the folder path?
This is what i usually use:
string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Note that this returns the directory of the assembly that contains the currently executing code (i assume this is your main executable).
To get the parent directory of the resulting path, you can also use
Path.GetDirectoryName(appDirectory);
I would advice against depending on the Visual Studio project structure in your code, though. Consider adding the images folder as content to your application, so that it resides in a subdirectory in the same directory as your executable.
If you are just trying to reference a directory with a fixed relationship to another, then you can just use the same .. syntax you'd use at the command line?
You should also use the methods in the Path class (eg Path.Combine) rather than all that string manipulation.

Read a file from an unknown location?

I have got this read file code from microsoft
#"C:\Users\computing\Documents\mikec\assignment2\task_2.txt"
That works fine when im working on it, but when i am to hand in this assignment my lecturer isn't going to have the same directory as me.
So i was wondering if there is a way to read it from just the file the program is held in?.
I was thinking i could add it as a resource but im not sure if that is the correct way for the assignment it is meant to allow in any file.
Thanks
You can skip the path - this will read file from the working directory of the program.
Just #"task_2.txt" will do.
UPDATE: Please note that method won't work in some circumstances. If your lecturer uses some automated runner (script, application whatsoever) to verify your app then #ken2k's solution will be much more robust.
If you want to read a file from the directory the program is in, then use
using System.IO;
...
string myFileName = "file.txt";
string myFilePath = Path.Combine(Application.StartupPath, myFileName);
EDIT:
More generic solution for non-winforms applications:
string myFilePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), myFileName);
If it is a command line application, you should take the file name as a command line argument instead of using a fixed path. Something along the lines of;
public static void Main(string[] args)
{
if (args == null || args.Length != 1)
{
Console.WriteLine("Parameters are not ok, usage: ...");
return;
}
string filename = args[0];
...
...should let you get the filename from the command.
You could use the GetFolderPath method to get the documents folder of the current user:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
and to exemplify:
string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string file = Path.Combine(myDocuments, #"mikec\assignment2\task_2.txt");
// TODO: do something with the file like reading it for example
string contents = File.ReadAllText(file);
Use the relative path.
you can put your file inside the folder where your application resides.
you can use Directory.GetCurrentDirectory().ToString() method to get the current folder of the application in. if you put your files inside a sub folder you can use
Directory.GetCurrentDirectory().ToString() + "\subfolderName\"
File.OpenRead(Directory.GetCurrentDirectory().ToString() + "\fileName.extension")
StreamReader file = new StreamReader(File.OpenRead(Directory.GetCurrentDirectory().ToString() + ""));
string fileTexts = file.ReadToEnd();

Categories

Resources