Configuration Builder - search through subfolders for JSON files - c#

I'd like to know how to set a ConfigurationBuilder to search through all subfolders for JSON files not only in Base Path itself.
var testDataBuilder = new ConfigurationBuilder();
var basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "myData");
testDataBuilder.SetBasePath(basePath);
testDataBuilder.AddJsonFile("myData.json");
testDataBuilder.AddJsonFile("myDataInSubCatalogue.json"); //HOW TO REACH THAT?
return testDataBuilder.Build();

First of all, if you know the names and locations of the files it's far safer to add them explicitly. Adding arbitrary configuration files without some way of checking their validity is a great way to get hacked.
AddJsonFile accepts a path but doesn't care where it points. There's no restriction that forces it to look into the current folder. That path could be a relative or absolute path. It could point to a remote shared folder too, allowing multiple clients to use a centralized configuration file.
You could enumerate all *.json files under the current folder and add them one after the other, eg :
var jsonFiles=Directory.EnumerateFiles(".","*.json", SearchOption.AllDirectories);
foreach(var path in jsonFiles)
{
builder.AddJsonFile(path);
}

Related

how to read a file from a different project?

how to read a file from a different project?
I have a solution:
Solution1
-MyProject
-MyProject.Artifacts
----Message.XML
-MyProject.Tests
I am attempting to read the contents of Message.XML from MyProject.Tests.
How do I read the contents of Message.XML from MyProject.Tests?
Unfortunately, right now I'm doing something like this, but it's not very pretty:
var currentDir = Directory.GetCurrentDirectory();
var parentDir = Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName;
var parentParentDir = Directory.GetParent(Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName).FullName;
var parentParentParentDir = Directory.GetParent(Directory.GetParent(Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName).FullName).FullName;
You can store a path to the file in app settings of app.config / web.config using that read the file contents.
That way if you need to deploy your software in a different way you have the flexibility
If your path is fixed, you can write the path like "c:\projects\solution ... Message.xml"
If you want a relative path, the simplest way is this:
var DI = new DirectoryInfo("..\\..\\..\\..\\Your Folder\\Message.XML");
This path is started from CurrentDirectory and goes four folders up and the one folder down and finds the file.

How to GetFileReference to an Azure blob/file if I have the _full_ absolute uri?

In my database I have the full absolute Uri to our azure files.
eg.
https://<snip>.file.core.windows.net/share1/Brand1/Export_2017-05-11-12-54.xml
https://<snip>.file.core.windows.net/share1/Brand1/asdfasdfasd.xml
https://<snip>.file.core.windows.net/share1/Brand2/PewPew%20-%20Sample-78206580-1dd8-4de2-9b92-002bdca861a5.xml
Please note:
Azure files Share name e.g. share1
The file names have one ore more / in em. e.g. brand1/blah.xml
I'm trying to see if the file exists and then do stuff with it (e.g. download it, whatever).
I need to get a File Reference to this item first. I've done all the ceremony to set that up (SAS, etc).
This is how I get a file reference to a file:
var cloudFile = ShareRootDirectory.GetFileReference(fileName);
if the fileName = "Brand1/Export_2017-05-11-12-54.xml it would work (note: no share or https://.... there.)
otherwise I get an error.
Is there some way, given a full absolute uri to a file on azure, can I pass something to my previously setup ShreRootDirectory to get/check the file? Or do I need to do it another way?
Is there some trick?
Note:
- I have a share folder (for files)
- Filenames have / in them which gives the illusion of folders.
Here's a screen shot of me doing this:
var tempCloudFile = new CloudFile(new Uri(fileName));
If you have access to storage credentials, you can use the following override of CloudFile to get a reference for that file and then perform operations on that file. For example, I get a reference for CloudFile below and checking for its existence.
var cred = new StorageCredentials(accountName, accountKey);
var file = new CloudFile(new Uri("https://<snip>.file.core.windows.net/share1/Brand1/Export_2017-05-11-12-54.xml"), cred);
var exists = file.Exists();

How to get a file full path in c# with Path.GetFullPath

I am trying to get the full path a file by its name only.
I have tried to use :
string fullPath = Path.GetFullPath("excelTest");
but it returns me an incorrect path (something with my project path).
I have read somewhere here a comment which says to do the following:
var dir = Environment.SpecialFolder.ProgramFilesX86;
var path = Path.Combine(dir.ToString(), "excelTest.csv");
but I do not know where the file is saved , therefore I do not know its environment.
can someone help me how to get the full path of a file only by its name?
The first snippet (with Path.GetFullPath) does exactly what you want. It returns something with your project path because the program EXE file is located in the project\Bin\Debug path, which is therefore the "current directory".
If you want to search for a file on a drive, you can use Directory.GetFiles, which will recursively search for a file in a directory given a name pattern.
This returns all xml-files recursively :
var allFiles = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories);
http://msdn.microsoft.com/en-us/library/ms143316%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/ms143448.aspx#Y252
https://stackoverflow.com/a/9830162/2196124
I guess you're trying to find file (like in windows search), right ?
I'd look into this question - you will find all files that has that string in their filename, and from there you can return full filepath.
var fileList = new DirectoryInfo(#"c:\").GetFiles("*excelTest*", SearchOption.AllDirectories);
And then just use foreach to do you manipulations, e.g.
foreach(string file in fileList)
{
// MessageBox.Show(file);
}
What you're looking for is Directory.GetFiles(), you can read up on it here. The gist of it is, you'll pass in the file path and the file name, and you'll get a string array back. In this instance, you can assume top level with C:\. It should be noted, that if nothing is found, the string array will be empty.
You have passed a relative file name to Path.GetFullPath. Microsoft documentation states:
If path is a relative path, GetFullPath returns a fully qualified path that can be based on the current drive and current directory. The current drive and current directory can change at any time as an application executes. As a result, the path returned by this overload cannot be determined in advance.
You cannot get the same full path name from a relative path unless your current directory is the same each time you invoke the function.

How to create a new path that contains the same path as the source but with a different root?

I'm about to develop a software in C# that must select random folders (in a scenario with 10.000 folders more or less) that follow these rules:
select only the ones which contains files;
the software must stop the selection when the size of selected folder is 8GB;
when I copy a single folder, I need to keep the whole path of that folder (if c:\folder\temp\hello is the copied one, I want to keep d:\COPIED\folder\temp\hello);
I think I will do somethings like:
analyze the whole list of folder starting from an assigned root;
select random "line" in this list, moving it to the "selected list", counting the size;
when I reach 8GB, I stop this first phase, and I start to copy it;
I think here it is not a big trouble. What do you think about? Any suggestions?
My real problem will to "recreate" the whole path for each single folder when I move it.
How can I do it? Create folder for each level with C# API or is there a workaround?
So the last paragraph is the question? I understand it in the following way:
How to create a new path that contains the same path as the source but
with a different root?
Then you can use the Path class and it's static methods + String.Substring to get the new path.
D:\Copied is your root destination folder which you use in Path.Combine. Then you have to add the old-path without it's root-folder(there is no method in Path for this, i'll use Substring):
var rootDest = #"D:\Copy"; // your root directory
var pathSource = #"C:\Test\Test.txt"; // a sample file
var root = Path.GetPathRoot(pathSource); // C:\
var oldPathWithoutRoot = pathSource.Substring(root.Length); // Test\Test.txt
var newPath = Path.Combine(rootDest, oldPathWithoutRoot); // D:\Copy\Test\Test.txt
Then use File.Copy to copy all files in the folder from the old to the new path.
You have to check if the directory exists and create it otherwise:
var targetDir = Path.GetDirectoryName(newPath);
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir); // D:\Copy\Test
}
File.Copy(pathSource, newPath);

how can i resolve a relative path in both a web/windows app in c#

I have an assmebly that will be used in both a desktop app and an asp.net website.
I need to deal with relative paths (local files, not urls) in either situation.
How can i implement this method?
string ResolvePath(string path);
Under a web envronment, id expect the method to behave like this (where d:\wwwroot\mywebsite is the folder iis points at):
/folder/file.ext => d:\wwwroot\mywebsite\folder\file.ext
~/folder/file.ext => d:\wwwroot\mywebsite\folder\file.ext
d:\wwwroot\mywebsite\folder\file.ext => d:\wwwroot\mywebsite\folder\file.ext
for a desktop environment: (where c:\program files\myprogram\bin\ is the path of the .exe)
/folder/file.ext => c:\program files\myprogram\bin\folder\file.ext
c:\program files\myprogram\bin\folder\file.ext => c:\program files\myprogram\bin\folder\file.ext
I'd rather not inject a different IPathResolver depending on what state its running in.
How do I detect which environment I'm in, and then what do i need to do in each case to resolve the possibly-relative path?
Thanks
I don't think the original question was answered.
Let assume you want "..\..\data\something.dat" relative to, lets say the executable in "D:\myApp\source\bin\". Using
System.IO.Path.Combine(Environment.CurrentDirectory, relativePath);
will simply return "D:\myApp\source\bin..\..\data\something.dat" which is also easily obtained by simply concatenating strings. Combine doesn't resolve paths, it handles trailing backslashes and other trivialities. He probably wants to run:
System.IO.Path.GetFullPath("D:\myApp\source\bin..\..\data\something.dat");
To get the a resolved path: "D:\myApp\data\something.dat".
The website binaries are copied to a temp folder when the application runs - so you usually can't get the relative path from the excecuting assembly.
This may not be a sensible way of doing this - but what I did to solve this problem was something like this:
if (filepath.StartsWith("~"))
{
filepath = HttpContext.Current.Server.MapPath(filepath);
}
else
{
filepath = System.IO.Path.Combine(Environment.CurrentDirectory, filepath);
}
This is because on the web version - a relative path has a ~ at the front - so I can tell if it's come from the web.config or the App.config.
As mentioned in John's comment, relative to what? You can use System.IO.Path.Combine method to combine a base path with a relative path like:
System.IO.Path.Combine(Environment.CurrentDirectory, relativePath);
You can replace Environment.CurrentDirectory in the above line with whatever base path you want.
You could store the base path in the configuration file.

Categories

Resources