Read from a file not found in the startup project - c#

My web solution has a number of projects.
The startup project is called: "Bob"
"Bob" has a reference to "Gill" project.
Inside "Gill", there is a file inside that i want to read. "Gill/One/Two/hi.txt"
I have some code in Bob, that calls some code inside the "Gill" project that tries to access the above txt file:
File.ReadAllText(#"~/One/Two/hi.txt")
That does not find the file.
I have marked the file build as
Content
I have marked Copy to Output Directory as:
Copy if newer
What's the approach to getting access to the file?

If you've set the file to Copy To Output Directory, this will be in the bin directory of your application.
Changing Igor answer slightly, you could do
var root = System.Web.Hosting.HostingEnvironment.MapPath("~/bin");
var filePath = System.IO.Path.Combine(root, "One", "Two", "hi.txt");
if(System.IO.File.Exists(filePath)) {
var allText = System.IO.File.ReadAllText(filePath);
}
Which will resolve the bin directory for your application, where your file will be rooted.

try file path as
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin\\One\\Two\\hi.txt");
And set
Build Action: none
Copy to output: Copy always (or copy if newer)

I believe the ~ is used by .NET webform and only be allowed by Server.MapPath (https://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath(v=vs.110).aspx)
You could get the File by new System.IO.FileInfo(#"One/Two/hi.txt");

You need to
Make sure the file has been copied to your web site. You cant read from it if it does not exist.
Put together the file path correctly. The executing code does not directly know about ~ as a path character, you have to translate that into a root path of the website for any types in the System.IO namespace like File or Path. The best way to do that is to use HostingEnvironment.
Code:
var root = System.Web.Hosting.HostingEnvironment.MapPath("~");
var filePath = System.IO.Path.Combine(root, "One", "Two", "hi.txt");
if(System.IO.File.Exists(filePath)) {
var allText = System.IO.File.ReadAllText(filePath);
}
Files marked as Content and Copied referenced in outside projects (that are in turn referenced by the web project) will have their content copied relative to the bin folder of the web application. In this case add bin to the root path like so:
var root = System.Web.Hosting.HostingEnvironment.MapPath("~/bin");

Related

Determine FilePath to Resource in C#

I have a CSV file in my Visual Stuido 2010 solution and I'm wondering how I can determine the absolute path to that CSV file. I need it to be dynamic as the path does change depending on where the project file is located on a User's filesystem.
Thanks for the assistance.
If the CSV file is in the working directory of your application, you can get the absolute path using the Path.GetFullPath Method:
var result = Path.GetFullPath("file.csv");
// result == #"C:\Users\...Studio 2010\Projects\MyProject\bin\Debug\file.csv";
A path can be either absolute or relative to some location (often the location of the executable). If you have a CSV file in your project you could set in its properties to be automatically copied to the output folder (Copy to Output Directory: Copy always) and in your application use relative path:
using (var csv = File.OpenRead("test.csv"))
{
...
}
Use Path.GetFullPath Method
You can use
string exedir = Path.GetDirectory(Assembly.GetExecutingAssembly().Location)
to get main exe dir.
Then you could append what you like. E.g.
csv_path = Path.Combine(exedir, "my_csv_file.csv")
or
csv_path = Path.Combine(exedir, #"subdir1\subdir2\my_csv_file.csv")

Includes directory in build path

I want to be able to add a directory containing a bunch of files to my project. This directory will need to be included in the build. I then need to be able to get the path of this directory at runtime.
Is there a way I can do this?
Cheers.
You can add the directory with all the files and set the property of each files as follows. This will make sure that all the files will be copied to running directory.
Build Action : Content
Copy Always : Copy Always (Depends on you need)
Access Files in the directory at run time
You can access using relelative path
bool isFileExisit = File.Exist("DirectoryName/FileName");
Access File with full path
String fullFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DirectoryName", "FileName");
Include the folder to the project, and set Copy to output directory property to true.
To reference application path use System.AppDomain.CurrentDomain.BaseDirectory
You need to add the files to your project and mark them as content files.
Then, to access them at run-time use the following code snippet:
string[] resourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames();
foreach (var resourceName in resourceNames)
{
if(resourceName.StartsWith("<assembly short name>.<directory name>"))
{
// do something
}
}

Get a file path in c# [closed]

I want to use the image smile.jpg. I've saved the jpg file into location ../project/Cam/bin/Debug/smile.jpg (this part of path is static)
But the previous path is dynamic, can anyone give me an idea?
Not very clear which path is which, but try to "play" with
Assembly.GetExecutingAssembly and Path.GetDirectoryName
//THIS RETURNS YOU A FOLDER WHERE YOUR APPLICATION RUNS
var exeutingFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
and
//COMBINE EXECUTING FOLDER WITH RELATIVE PATH YOU HAVE
var resultinPath = Path.Combine(executingFolder, YOUR_PATH);
Do you want to get the full path from the relative path?
If so, you can use System.IO.Path.GetFullPath()
e.g.
string fullPath = System.IO.Path.GetFullPath("../project/Cam/bin/Debug/smile.jpg");
There are several solutions to the underlying problem of loading an image that is shipped with the application:
Solution 1: Resources
If it is not necessary that the image file is present, you can simply add the image to your program's resources and assign it in the designer. The image file then doesn't have to be deployed.
To do so, add the image file to your project, then, drag it to the "Resources" tab of your projects properties.
Solution 2: Files copied to the output folder
Maybe you want your images in your output folder and load them from files at runtime. Then you should really avoid making any assumptions about the folder, but instead do the following:
Add the image files to your project and set their built type to "none" and have them be always copied to the output folder. If you build your project, the image files should now be in /bin/debug or /bin/release.
In your code, build a path to the files using the assembly folder
This code gets the assembly folder and assembles a path name to an image named "smiley.png":
string assemblyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string smileyPath = Path.Combine(assemblyPath, "smiley.png");
In case you added the images to a folder within your project, the folder will also be created in the output folder. For example: if you put your images into a folder "images", there will be a folder "images" in bin/debug or bin/release. In that case you can safely make the assumption that the following code will work:
string assemblyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string imagePath = Path.Combine(assemblyPath, "images");
string smileyPath = Path.Combine(imagePath, "smiley.png");

How to get a path from a directory in a C# console application?

Say I have this file structure
Soultion-> Folder1 -> FileIwant.html
So this could be something like C:\Soultion\Folder1\FilterIwant.html
Now I need to read this file into my application. I can't just hardcode it since when I give it to someone else they might put it on F: drive or something.
Or when I create a msi file the path might be completely different. So how can I say maybe take
"Folder1\FilterIwant.html"
and use that to get the folder path regardless of where they put it?
Edit
I tried Path.GetFullPath but I land up in the bin/debug directory. But my file is not in that directory. I think it is a couple directories before. Also if I make a msi file will I have bin/debug directory?
Why is a file which is used as part of your application not in the same folder as the application? It sounds to me like you should set the properties on that file to copy to the output folder when you do a build.
Doing that will make sure your file is in the bin\debug folder.
EDIT:
either that or you should be placing your files in one of the special folders, app data or my documents spring to mind.
When Visual Studio compiles your project, it will be putting the output into the bin\debug directory. Any content files that you want to reference must also be copied to those locations, in order for your app residing in that directory to be able to read that file.
You have two choices:
either you set the Copy to Output Directory property on your FilterIwant.html to Copy if newer; in that case, if the file has changed, it will be copied to the output directory, and you should be able to reference it and load it there
or
you just define a path in your app.config, something like DataPath, and set it to your folder where the file resides. From your app, you then create the full path name for that file as Path.Combine(AppSettings["DataPath"], "FilterIwant.html") - with this approach, you become totally independant of where the file really is and you don't need to move around anything. Also: this gives you the opportunity to create an admin/config utility for your users later on, so that they can pick any directory they like, and your app will find those files there.
In my console app, I started with the debug directory until i found the closest parent folder I wanted.
static void Main(string[] args)
{
Console.WriteLine("Start");
var debugDir = Environment.CurrentDirectory;
DirectoryInfo di = new DirectoryInfo(debugDir);
var searchDir = "";
while (!di.FullName.ToLower().EndsWith("Folder1"))
{
if(di.FullName.ToLower().EndsWith(":")) //if you went too far up as in "D:" then
break;
di = di.Parent;
}
Console.WriteLine(di.FullName);
}
You need the help of System.Io.Path class:
GetFullPath: Returns the absolute path for the specified path string.
Edit:
You might also need the application directory - this is where your application will be installed:
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
Path.GetFullPath
Edit
The bin/Debug path will not be present when you run your installed application (unless you specifically tell the installer to use that subdirectory, of course).
You probably want to pass the full path as a command line argument. You can then get the argument using the args parameter of the Main method. To convert a relative path to an absolute one you can use Path.GetFullPath:
using System;
using System.IO;
public class CommandLine
{
public static void Main(string[] args)
{
// The path is passed as the first argument
string fileName = arg[0];
// get absolute path
fileName = Path.GetFullPath(fileName);
// TODO: do whatever needs to done with the passed file name
}
}

Problem with access to file

I have winforms application and it has reference to library MyLibrary.
MyLibrary has method:
string[] GiveMeNamesOfAirports()
{
string[] lines= File.ReadLines("airports.txt");
foreach(string line in lines)
...
}
And when I run my Winforms application:
I get error:
file couldn't be find.
I was trying other function:
string[] lines = File.ReadAllLines(Path.Combine(System.Environment.CurrentDirectory, "airports.txt"));
string[] lines = File.ReadAllLines(Path.Combine(Assembly.GetExecutingAssembly().Location, "airports.txt"));
string[] lines = File.ReadAllLines(Path.Combine(Assembly.GetAssembly(typeof(Airport)).Location, "airports.txt"));
File is in project MyLibrary ( I see it in solution, and it is in folder of MyLibrary.
I set Copy to ouptput directory to Copy always, and Build Action to Content.
It is unwise to use a relative path name for a file. Your program's working directory might change and will then fail to find the file. Generate the absolute path name of the file like this:
public static string GetAbsolutePath(string filename) {
string dir = System.IO.Path.GetDirectoryName(Application.StartupPath);
return System.IO.Path.Combine(dir, filename);
}
Usage:
string[] lines= File.ReadLines(GetAbsolutePath(#"mylibrary\airports.txt"));
For System.Environment.CurrentDirectory to work you will need to have the "airports.txt" file in the bin\release or bin\debug (depending on what buid you are running) directory when running from within VS.
The two using the Assembly location won't work because Location includes the Assembly name, so it has more than just the path.
Does this mean MyLibrary has a file called airports.txt?
If so, you'll want to be sure the file is set to be included in the build output. Right-click on the file in Visual Studio and choose Properties. From the Properties window, there is a Copy to Output Directory property you can set to Copy Always and you should have no more problems.
Every one of your methods above is assuming the file "airports.txt" is in the same folder as your executable. Do note that by Visual Studio defaults, the debug version of your executable (which is used when debugging) is at bin\Debug and the release version you'll give to your users is at bin\Release.

Resources