I have a file path which I access like this
string[] pathDirs = { Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\")),
"config", "file.txt" };
string pathToFile = Path.Combine(pathDirs);
When I run the build from within visual studio it gets the config directory from the root directory of the project but when I publish the build and run the program from the published build I get the error
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\<user>\AppData\Local\Apps\2.0\GA3VWRPE.G83\KDK3Q6QC.VP1\sv20..tion_333839f4362dc717_0001.0000_958d209d94853f42\config\file.txt'.
I'm unsure how to access this directory and file in the published build. How would I do this?
To get the path to the executable, you can use Assembly.GetExecutingAssembly().Location, which could be incorporated into your code like:
string filePath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location), "..", "..", "config", "file.txt"));
Thanks to #ManiVI for that comment.
Go to Solution Explorer and click Show All Files
Go to file.txt, right-click and select Include In Project
in Properties
Build Action: Content,
Copy To Output Directory: Copy always
Once I followed these steps the published program managed to find file.txt.
Related
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")
With asp.net core 1.0 There are lots of functionality added. But there is not way to get Bin Folder path.
Can anyone please know how we can get the bin folder path for asp.net core 1.0 application.
Alternative way (corresponds to the AppDomain.BaseDirectory):
AppContext.BaseDirectory
This works to retrieve the assembly's directory, from which we can determine the bin location.
var location = System.Reflection.Assembly.GetEntryAssembly().Location;
var directory = System.IO.Path.GetDirectoryName(location);
System.Console.WriteLine(directory);
Output
C:\MyApplication\bin\Debug\netcoreapp1.0
Well, the bin folder does exists but it is moved to artifacts folder next to the solution file. Since ASP.NET Core RC 1 compiles everything in memory, you will find empty bin folder. But if you set "Produce output on build" option to true (Right click Project file -> Properties and Build tab) then you will find the generated files in bin folder.
I don't think so there is any direct property available as to get the path of this but you can use the same solution pointed out by #Nikolay Kostov to get application path. And then using System.IO classes jump to bin folder.
Code updated to for ASP.NET Core as mentioned here.
http://www.talkingdotnet.com/get-application-wwwroot-path-aspnet-core-rc2/
public Startup(IHostingEnvironment env, IApplicationEnvironment appenv)
{
string sAppPath = env.ContentRootPath;
string sRootPath = Path.GetFullPath(Path.Combine(sAppPath, #"..\..\"));
string sBinFolderPath = #"artifacts\bin\" + appenv.ApplicationName;
string sBinPath = Path.Combine(sRootPath, sBinFolderPath);
}
You can't really get the /bin/ folder since it is not relevant to your project and the ASP.NET environment doesn't know what a /bin/ folder is.
And also there isn't exactly a /bin/ folder. You may want to read this article: http://docs.asp.net/en/latest/conceptual-overview/understanding-aspnet5-apps.html
But you can get the so called ApplicationBasePath which is the directory in which you application runs:
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
string baseDir = appEnv.ApplicationBasePath;
// Other startup code
}
AppDomain.CurrentDomain.BaseDirectory;
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?.
I have a Xamarin-Studio App for Android and I simply want to download files and save them locally. But when I try to create a file in the files folder I get an exception:
File.Create("data/data/com.company.app/files/newFile.png");
gives me:
System.UnauthorizedAccessException
Access to the path 'data/data/com.company.app/files/newFile.png' is denied.
What am I doing wrong?
You should use Environment or IsolatedStorage. For example:
var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var filename = Path.Combine(path, "newFile.png");
I am coding Xamarin with VS2013. I had the access denied error for a directory created with the application I am writing. My application creates a directory called /storage/emulated/0/POIApp by concatenating via:
System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, "POIApp");
I found that I had to use VS2013 to edit the "properties" of my application (POIApp), i.e., right-click the project icon in the solution explorer; choose properties from the pop-up menu. A new tab appears in the main VS2013 window. On the left there are a few choices, e.g., Application, Android Manifest, Android Options, Build, etc. Choose "Android Manifest". At the bottom of the main panel is a section "required permissions". My problem was solved when I checked "READ_EXTERNAL_STORAGE" and "WRITE_EXTERNAL_STORAGE".
Add the following permission to Android.Manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I finally realized that File.create() was not the problem. I had code like this:
string tmpFilePath = FilesDir.AbsolutePath.stringByAppendingPath (f.Path);
Java.IO.File tmpFile = new Java.IO.File( tmpFilePath);
tmpFile.Mkdirs ();
Yet, Mkdirs() does not only create all intermediate directories – as I had assumed – but also creates a directory at the file path itself. So the file could not be created because there already was a directory with the same name.
The correct way is:
string tmpFile = FilesDir.AbsolutePath.stringByAppendingPath (f.Path);
Java.IO.File tmpParentFolder = new Java.IO.File(tmpFile).getParentFile();
tmpParentFolder.Mkdirs ();
In my defense, an FileExistsAndIsDirectory exception would have been much more helpful than the UnauthorizedAccessException
Using Mono, I think must be the same as in Xamarin Studio.
var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
File.Create(path + "newFile.png");
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'.