File ReadAllText is getting a wrong path (C#) - c#

I have a local project that in the future will be in a pipeline.
Because of this, I need to use a relative path to get and read a json file.
But using the File.ReadAllText I'm obtaining the following answer:
> File.ReadAllText("MyJsonFiletoRead.json", Encoding.Default)
System.IO.FileNotFoundException: Could not find file 'C:\Users\15071\MyJsonFiletoRead.json'
Note that 'C:\Users\15071' is not the project folder, this is my windows user folder.
My struct is here:
C:\Projetcs\MyProjectTest -->> Project folder
C:\Projetcs\MyProjectTest\MyClass.cs -->> The class where I'm calling the ReadAllText
C:\Projetcs\MyProjectTest\MyJsonFiletoRead.json -->> My json file that I'm trying to find
I have tried the following commands to check my PATH, but all answer is wrong:
> Environment.CurrentDirectory
"C:\\Users\\15071"
> Directory.GetCurrentDirectory()
"C:\\Users\\15071"
AppDomain.CurrentDomain.BaseDirectory
"c:\\program files (x86)\\microsoft visual studio\\2019\\community\\common7\\ide\\commonextensions\\microsoft\\managedlanguages\\vbcsharp\\languageservices\\DesktopHost\\"
Has somebody a solution to fix this?
Note: If I use the full path, it works:
File.ReadAllText("C:/Projetcs/MyProjectTest/MyJsonFiletoRead.json", Encoding.Default)

If the file is located at the same folder of your executable file, you just need to pass the file name:
File.ReadAllText("MyJsonFiletoRead.json", Encoding.Default);
If the file is located at a relative path from the folder where your executable file is located, you can get the Assembly Location and combine it with a relative path:
var path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..\\..\\MyJsonFiletoRead.json");
File.ReadAllText(path, Encoding.Default);

You need to find the current folder and then read the file
var currentFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
File.ReadAllText(currentFolder + "/MyJsonFiletoRead.json")

Related

Adding content files to and accessing content files from a web service

I want to include an XML file in the bin directory of my web application/web service. I've included the bin folder in my project in Visual Studio and added the file. I set its Build Action to "Content" and Copy to Output Directory to "Copy Always". When my code goes to find it, I use
string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!dir.EndsWith(#"\")) dir += #"\";
to get the directory and return it as appPath, where appPath is (unescaped version):
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\vs\0c7655f\d4908928\assembly\dl3\5cf9fd67\fdc52284_ffa7d201\
then I append the file name of my XML file (where string filename = "myXmlFile.xml") to read it:
StreamReader reader = new StreamReader(appPath + filename);
But I get an exception on that line of code, that it could not find my file. I am handling for escaping of the slashes fine, so it is not that. When I checked the physical directory that the path points to, it was not copied to that directory, and that is the cause of the exception. So how do I get my file to get copied there?
How about using HostingEnvironment.ApplicationPhysicalPath
var dir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin\\filename.xml")
See related question how to get the application path in asp.net?.

c# starting a .exe file from current file path + folder + exe file

Im trying to have a exe file opened on click, its going to be in a subfolder of a file path, I dont want to put in c:\folder due to file install will be different for each user, I would like to use file path + another folder in that file path to + "file.exe"
Any ideas?
you can use this code smple
static void Main(string[] args)
{
Process.Start(<"your file path");
}
for example if you wish to run notepath++ then
you path will be=#"C:\Program Files (x86)\Notepad++\Notepad++.exe

Save/Copy a file in a directory from another

using : asp .net mvc 4.0, c# , vs10
strFilePath holds a path of a existing file in a directory. I want to save/copy the file into my application's uploads directory.
how could i do this. I am trying something foolish, and searching the internet and feeling helpless.
string filePath = "foo.txt";
//var path = Path.Combine(Server.MapPath("~/Uploads"), filePath);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Copy(filePath, "~/Uploads");
}
~ symbol is not recognized by File.Copy
Convert virtual path to physical path first and then do the copy.
System.IO.File.Copy(filePath, Server.MapPath("~/Uploads"));
Also, You need permission to the folder where you are copying. You may need to Impersonate if the above does not work.

Could not find xml file

I'm studing wcf. In my test project Service read data from xml file and then send it to client. Data is array of type "myClass".
Service class has a function
Collapse | Copy Code
private XDocument GetDB()
{
string filePath = "SampleDB.xml"
return XDocument.Load(filePath);
}
This function works when I run the service application. But when I call service from client it doesn't work.
The copy of xml file located in bin->debug folder. but when i run programm, I see exception like this
Could not find file 'C:\Program Files (x86)\Microsoft Visual Studio
10.0\Common7\IDE\SampleDB.xml'.
How can I solve this?
Obviously, give the full path to your file, should end with bin\debug\SampleDB.xml
You have to specify the xml file using Server.MapPath.
string filePath = Server.MapPath("SampleDB.xml");
That's the solution of "Could not find file 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\SampleDB.xml'.

Relative path in .NET

I am running my C# application from "D:\App\program.cs". My application needs to execute a file placed in "C:\Program Files\software\abc.exe".
How can I set the relative path in my program to execute the "abc.exe"?
To answer the question how to get a path that shows the relative location of pathB from pathA. You can use the Uri class to get the relative path.
string pathA = #"C:\App\program.cs";
string pathB = #"C:\program files\software\abc.exe";
System.Uri uriA = new Uri(pathA);
System.Uri uriB = new Uri(pathB);
Uri relativeUri = uriA.MakeRelativeUri(uriB);
string relativeToA = relativeUri.ToString();
Console.WriteLine(relativeToA);
This yields "../program%20files/software/abc.exe" for the relative path.
I have changed your example from D to C though because you can't have a relative path for two locations on different drive letters, although the above code still works, just yields the absolute.
OR if the c# bit is a red herring, and as I now understand you want to run a batch file:
in batch file put:
cd c:\program files\software\
abc.exe
abc.exe will then execute from software folder and not folder of the batch file.
You shouldn't be using relative path for referring something from Program Files. I would recommend to use Environment.GetFolderPath (and Environment.SpecialFolder) to get path to Program Files and then use some config setting to get reminder path to the program.
It's not clear what you mean by "set relative path", but if you're using Process and ProcessStartInfo to run the executable, I would suggest that you use an absolute path to specify the executable, and ProcessStartInfo.WorkingDirectory to tell the process where to run (so that relative paths will be evaluated appropriately within the new process).
EDIT: If you want the batch file to run c:\Program Files\Software\abc.exe then the contents of the batch file should be just:
"c:\Program Files\Software\abc.exe"
(Note the quotes to allow for space.)
I don't see what this has got to do with relative pathnames though.
If the application is in Program Files then you can create a batch file like
"%ProgramFiles%\software\abc.exe"

Categories