path to subfolder for a text file - c#

StreamReader content1 = File.OpenText("../DATA/heading.txt");
I have a txt file in a subfolder called DATA, I am trying to access this file from code but the code goes to the .net runtime directitory and not the application directory, thanks for the help

string filePath = Server.MapPath("/Data/heading.txt");
StreamReader content1 = File.OpenText(filePath);

Try using the Application's Entry assembly to get your text file path like this.
Assembly asm = Assembly.GetEntryAssembly();
string appDir = Path.GetDirectoryName(asm.Location);
string filePath = Path.Combine(appDir, "../DATA/heading.txt");
StreamReader content1 = File.OpenText(filePath);
This will work for any application that starts as an exe.

Since you marked this as asp.net are you looking on the server from asp.net? If so try Server.MapPath http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx

From MSDN - http://msdn.microsoft.com/en-us/library/system.io.file.opentext.aspx
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
http://msdn.microsoft.com/en-us/library/system.io.directory.getcurrentdirectory.aspx
So your current directory is not set to your application directory.

Related

Referencing a file inside of a Project without using its absolute path?

I'm using StreamReader to dynamically replace content in an HTML template. The HTML file has been imported into my project.
Right now I'm having to referencing the HTML file a static location on my dev box because I'm not able to find the right syntax to reference it once it's been imported into my VS project.
How do I refer to the file without using an absolute path?
Current implementation for reference:
StreamReader reader = new StreamReader(#"C:\Users\n00b\Desktop\EmailTemplate.html");
{
body = reader.ReadToEnd();
}
One common thing I've seen is to put the file's location in a configuration file. This lets you change the file location at will without having to recompile.
You can add it as an embedded resource and extract it this way.
using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("<namespace>.Resources.EmailTemplate.html"))
per your comment
using (System.IO.StreamReader sr = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("<namespace>.Resources.EmailTemplate.html"))
{
body = sr.ReadToEnd();
}
There are 2 main ways to do this, In a desktop application, the current directory of the .exe is set to the directory where it is launched from by default. Unless that is changed by launching the .exe by a shortcut with special settings, or by another process using a special feature, it should be the default value. If that is the case, you can just use a relative path. For example, if you have a file named "data.txt" in a folder called "things" inside a folder called "stuff" in the same directory as your app, you can just us the relative path "stuff/things/data.txt" directly and Windows will work it out for you.
If you need to be absolutely sure you are targeting that file, even if the app launches with a modified current directory, you can get the .exe's path, and combine it with a relative path using System.IO.Path.Combine.
var appPath = Assembly.GetEntryAssembly().Location;
var filePath = "stuff/things/data.txt"
var fullPath = System.IO.Path.Combine(appPath, filePath)
If, for some reason, you need to up "up" from the application's directory, you can use ".." to represent that parent folder of a directory. So "../data.txt" would look in the folder that contains the current directory for a file named "data.txt".
You could also change the app's current directory when it starts to be the directory of the .exe, and then reference everything via relative path, as in the first example.
var appPath = Assembly.GetEntryAssembly().Location;
System.IO.Directory.SetCurrentDirectory(appPath);
I found two solutions to this:
If you don't care if the external file is visible in the build directory/installdir of your app:
StreamReader reader = new StreamReader(#"../../EmailTemplate.html");
{
body = reader.ReadToEnd();
}
If you want your external file to be invisible once compiled:
var embeddedResource = "<namespace>.EmailTemplate.html";
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedResource))
{
StreamReader sr = new StreamReader(stream);
body = sr.ReadToEnd();
}
Note the 2nd solution requires adding your external file and changing the build action to "Embedded Resource" on the properties menu of that file within Visual Studio.

Convert Relative Path to Absolute Path

I am trying to open a Help.txt file in windows Forms using a linkLabel. However unable to convert from absolute to relative path.
First, I try to get the absolute path of the exe file. Which is successful.
Second, get only directory of the exe file. Which is successful.
Third, I am trying to combine the directory with the relative path of the Help.txt file. Which is unsuccessful.
Exe file lives in -> \Project\bin\Debug folder, However the Help.txt file lives in \Project\Help folder. This is my code:-
string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
string Dir = Uri.UnescapeDataString(Path.GetDirectoryName(exeFile));
string path = Path.Combine(Dir, #"..\..\Help\Help.txt");
System.Diagnostics.Process.Start(path);
The result of my path is -> \Project\bin\Debug....\Help\Help.txt
You need to use Path.GetFullPath() to have the upper directory "../../" taken into account, see below :
string exeFile = new System.Uri(Assembly.GetEntryAssembly().CodeBase).AbsolutePath;
string Dir = Path.GetDirectoryName(exeFile);
string path = Path.GetFullPath(Path.Combine(Dir, #"..\..\Help\Help.txt"));
System.Diagnostics.Process.Start(path);
Per the MSDN of GetFullPath : Returns the absolute path for the specified path string.
Whereas Path.Combine Combines strings into a path.

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.

Getting the parentDirectory of a file in a unc path c# 2010

I need to identify first is this a UNCPath if so get the file directory
Is there a method to identify if a path is a UNC Path?
How do I get the file's parent.Parent.directory?
\\MyServer\\MySharedDrive\\MyDirectory\\MySubDirectory\\Myfile.csv
Wanted result and should work however deep
\\MyServer\\MySharedDrive\\MyDirectory
so that I can save another file to the above directory.
I guess I cannot do
Path.Combine("\\MyServer\\MySharedDrive\\MyDirectory",myNewFile.csv)
Any Suggestions?
Many thanks
To get parent directory and then creating a new path you can do:
string path = "\\MyServer\\MySharedDrive\\MyDirectory\\MySubDirectory\\Myfile.csv";
DirectoryInfo directory = new DirectoryInfo(Path.GetDirectoryName(path));
string finalPath = Path.Combine(directory.Parent.FullName, "myNewFile.csv"
To check if the path is UNC check this post.
From MSDN
Most members of the Path class do not interact with the file system
and do not verify the existence of the file specified by a path string
Again from MSDN on Path class
In members that accept a path, the path can refer to a file or just a
directory. The specified path can also refer to a relative path or a
Universal Naming Convention (UNC) path for a server and share name
Said that, you could write
string myUNCPath = #"\\MyServer\MySharedDrive\MyDirectory\MySubDirectory\Myfile.csv";
string myParent = Path.GetDirectoryName(Path.GetDirectoryName(myUNCPath));
string finalFile = Path.Combine(#"\\MyServer\MySharedDrive\MyDirectory","myNewFile.csv");
As a safety check you should execute two separate calls to Path.GetDirectoryName because if you have only one level deep of subdirectory then the result of Path.GetDirectoryName will be null
For example, if the initial UNC path is
string myUNCPath = #"\\MyServer\MySharedDrive\MyDirectory\Myfile.csv";
string myParent = Path.GetDirectoryName(myUNCPath);
if(!string.IsNullOrWhiteSpace(myParent))
{
myParent = Path.GetDirectoryName(myParent);
if(!string.IsNullOrWhiteSpace(myParent))
{
string finalFile = Path.Combine(myParent, "myNewFile.csv");
.....
}
}
For the part relative to your first question, the discovery of an UNC path is relatively easy.
See this article on Windows Dev Center about Paths and Files
Console.WriteLine(IsUNCPath(myUNCPath));
......
bool IsUNCPath(string pathToCheck)
{
return pathToCheck.StartsWith(#"\\");
}

How to copy an image to application folder?

I already know how to browse for an image using open file dialog. So let's say we already got the path :
string imagePath = "Desktop/Images/SampleImage.jpg";
I want to copy that file, into my application folder :
string appFolderPath = "SampleApp/Images/";
How to copy the given image to the appFolderPath programmatically?
Thank you.
You could do something like this:
var path = Path.Combine(
System.AppDomain.CurrentDomain.BaseDirectory,
"Images",
fileName);
File.Copy(imagePath, path);
where fileName is the actual name of the file only (including the extension).
UPDATE: the Path.Combine method will cleanly combine strings into a well-formed path. For example, if one of the strings does have a backslash and the other doesn't it won't matter; they are combined appropriately.
The System.AppDomain.CurrentDomain.BaseDirectory, per MSDN, does the following:
Gets the base directory that the assembly resolver uses to probe for assemblies.
That's going to be the executable path you're running in; so the path in the end (and let's assume fileName is test.txt) would be:
{path_to_exe}\Images\test.txt
string path="Source imagepath";
File.Copy(System.AppDomain.CurrentDomain.BaseDirectory+"\\Images", path);
\ System.AppDomain.CurrentDomain.BaseDirectory is to provide path of the application folder

Categories

Resources