C# absolute path with streamReader - c#

I have an issue with the reading a file in C#
I have two different locations for .exe (both different) and reading the same .xml file. So when I give the path like this:
TextReader textReader = new StreamReader(#"../../../TrajectoryGen/obstacleList.xml");
it is able to read from one location ( which is 3 folders behind as used in the path) but not from another location (which is only 2 folders behind)
How do I fix this problem so that it works from both folders?

First way, this relies on you knowing one of the parent folder's names.
const string FILENAME = "obstacleList.xml";
const string FOLDER = "TrajectoryGen";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
do
{
path = Path.GetDirectoryName(path);
} while (!Path.GetFileName(path).Equals(FOLDER, StringComparison.OrdinalIgnoreCase));
string filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
^^ You can also use a partial path in the FILENAME like the example below incase you need to into directories once you are at your "base" folder that you know the name of.
Second way blindly continues up directories
const string FILENAME = #"TrajectoryGen\obstacleList.xml";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
string filepath;
do
{
path = Path.GetDirectoryName(path);
//pump
filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
} while (!File.Exists(filepath));
Both require "using System.IO;" and both have no error handling implemented and will throw NullReferenceException if the file/folder is not found.
I purposely used the do-while loop because the definition of path will included the executable name.

Related

c# - How to assign resources folder to a string

I'm currently using this,
string finename = "text.txt"; //setting file name
//setting locations
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filepath = #"C:\User\Users\Documents\Files\Apple"; // <--- need to use Resources folder in the project folder here
//filename and location combining to be copied
string source = Path.Combine(filepath,filename);
string destination = Path.Combine(path,filename);
if (something=1)
{
File.Copy(source,destination, true); //copying
}
I've added all the files to the Resources now i need to refer to Resources folder instead of "filepath" here,
is there any way to assign the resources folder (& its contents) to a string so i can simply change the location? then i can use this code on other PC's also.
Edit -
Imagine i have orange,mango and apple folder inside the resource folder, and each of these 3 folders contain a text file with the name "text.txt".
And i need to copy one of these text files from each & every fruit folder on request & paste it on desktop.
Now i need to store the location of "Resources\apple" , "Resources\orange" & "Resources\mango" on 3 different strings so i can simply call them in the "string source = Path.Combine(filepath,filename)" part instead of older "filepath" to copy those text files from any of the fruit folder inside resources folder to the desktop.
thanks.
Get src or root folder path.
Combine root folder path with your resource folder path.
Combine result(root\resources) with your file name
Here you go, you will get exact path of file and now you can copy it to the destination.
Here is the implementation: This code is running on my machine.
/// <summary>
/// Here you just need to send fruit name
/// </summary>
/// <param name="fruitName">Name of fruit</param>
public void CopyFile(string fruitName)
{
string filename = "text.txt"; //setting file name
string resouceFolderName = Path.Combine("Resources", fruitName);
//Destination Path
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//CurrentDirectory return src\\Bin\\Debug so extracting src root folder path
string parentFolderPath = Directory.GetParent(Directory.GetParent(Environment.CurrentDirectory).FullName).FullName;
//combining parent folder path with resource folder name
string folderPath = Path.Combine(parentFolderPath, resouceFolderName); // <--- need to use Resources folder in the project folder here
//Checking if exist or not
if (!Directory.Exists(folderPath) || !Directory.Exists(path))
{
Console.WriteLine("Error");
return;
}
//filename and location combining to be copied
string source = Path.Combine(folderPath, filename);
string destination = Path.Combine(path, filename);
if (true)
{
File.Copy(source, destination, true); //copying
}
}
Note: Here I used test.txt and Resources string as a constant considering they won't change
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
What you are doing here is retrieving the path to your desktop and copying your .txt file from your filepath to there.
You are not copying the file onto your project "Resources" folder.
In case your file is there as #Prasad telkikar said, with the following code you would have the path to your's "Resource" folder and be able to access all the content inside it.
string path = Path.Combine(Environment.CurrentDirectory, "Resources");

putting files paths that in specific dir in array c#

How should I put files paths in a StreamReader array that located in a specific dir C#?
I tried this code in different ways but I didn`t got nothing of what I need and I need one path
string fileName = "myfile.ext";
string path1 = #"mydir";
string path2 = #"\mydir";
string fullPath;
fullPath = Path.GetFullPath(path1);
Console.WriteLine("GetFullPath('{0}') returns '{1}'",
path1, fullPath);
fullPath = Path.GetFullPath(fileName);
Console.WriteLine("GetFullPath('{0}') returns '{1}'",
fileName, fullPath);
fullPath = Path.GetFullPath(path2);
Console.WriteLine("GetFullPath('{0}') returns '{1}'",
path2, fullPath);
Not clear what you're trying to do, but maybe you want a list of files in a folder to a text file? If so, you could use this code:
static void SaveFileListingToText(string folder, string outputTxtFilePath)
{
string[] files = System.IO.Directory.GetFiles(folder);
System.IO.File.WriteAllLines(outputTxtFilePath, files);
}

Copy a specific file (.docx, .pdf, .pptx etc) form folder in C#

I am trying to copy a file (.docx, .pdf, .pptx etc) from a source folder(on server) to a destination folder(on client).
The user can choose which among the list of files that he wants to download. He selects the files and then downloads it(Copies it to his computer) to the destination path
dstnLocation= #"C:\Fldr\Docs;
My Code:
string sourceLocation = textBox2.Text;
string dstnLocation = #"C:\Fldr\Docs";
System.IO.FileInfo file = new System.IO.FileInfo(dstnLocation);
file.Directory.Create();
System.IO.File.Copy(sourceLocation, dstnLocation,true);
MessageBox.Show("Download Complete");
The problem is that it creates a file as "Docs"(where one has to use open with to open the file) and if I am not wrong then its because of the destination path. Could someone please tell what all am I doing wrong.
The source path is retrieved through database!
you need to concat otherwise you're destination location is just the folder not the file path destination
so do something like
var destFile = string.Format(#"{0}\{1}", dstnLocation, Path.GetFileName(sourceLocation));
then copy that
So code becomes
string sourceLocation = textBox2.Text;
string dstnLocation = string.Format(#"C:\Fldr\Docs\{0}", Path.GetFileName(sourceLocation);
if (! System.IO.Directory.Exists(dstnLocation))
{
System.IO.Directory.CreateDirectory(dstnLocation);
}
System.IO.File.Copy(sourceLocation, dstnLocation,true);
MessageBox.Show("Download Complete");
You are creating the file name incorrectly:
string dstnLocation = #"C:\Fldr\Docs";
System.IO.FileInfo file = new System.IO.FileInfo(dstnLocation);
This creates a file with the name "C:\Fldr\Docs" for example what you want is "C:\Fldr\Docs\myfilename.docx" if I am not mistaken?
Try this instead:
var filename = Path.GetFileName(sourceLocation);
string dstnLocation = Path.Combine(#"C:\Fldr\Docs", filename);
The problem here is that the destination requires an "output" file name.
This problem lies in this line of code
System.IO.File.Copy(sourceLocation, dstnLocation,true);
The dstnLocation needs to be concatenated with the output file name for example:
System.IO.File.Copy(sourceLocation, Path.Combine(dstnLocation,"Database.dbs"),true);

Streamreader to a relative filepath

I was wondering, if anyone could tell me how to point a StreamReader to a file inside the current working directory of the program.
E.g.: say I have program Prog saved in the directory "C:\ProgDir\". I commit "\ProgDir" to a shared folder. Inside ProgDir is another directory containing files I'd like to import into Prog (e.g. "\ProgDir\TestDir\TestFile.txt") I'd like to make it so that the StreamReader could read those TestFiles, even when the path to the directory has changed;
(E.G., on my computer, the path to the Testfiles is
C:\ProgDir\TestDir\TestFile.txt
but on the other person's computer, the directory is
C:\dev_code\ProgDir\TestDir\TestFile.txt
).
How would I get a StreamReader to be ale to read from TestFile.txt on the other person's computer? (to clarify, the filenames do not change, the only change is the path ProgDir)
I tried the following:
string currentDir = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(currentDir);
FileInfo file = new FileInfo("TestFile.txt");
string fullDirectory = directory.FullName;
string fullFile = file.FullName;
StreamReader sr = new StreamReader(#fullDirectory + fullFile);
( pulled this from : Getting path relative to the current working directory?)
But I'm getting "TestFile does not exist in the current context". Anyone have any idea as to how I should approach this?
Thank you.
Is the Folder "TestDir" always in the executable directory?
if so, try this
string dir =System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
string file = dir + #"\TestDir\TestFile.txt";
This will give you the path of the exe plus the folder inside it and the textfile
You can use the GetFullPath() method. Try this:
string filePath = System.IO.Path.GetFullPath("TestFile.txt");
StreamReader sr = new StreamReader(filePath);
A few things:
First, FileInfo.FullName gives the absolute path for the file, so you don't need to prepend the full directory path before the file in the StreamReader instance.
Second, FileInfo file = new FileInfo(TestFile.txt); should fail unless you actually have a class called TestFile with a txt property.
Finally, with almost every File method, they use relative paths already. So you SHOULD be able to use the stream reader on JUST the relative path.
Give those few things a try and let us know.
Edit: Here's what you should try:
FileInfo file = new FileInfo("TestFile.txt");
StreamReader sr = new StreamReader(fullFile.FullName);
//OR
StreamReader sr = new StreamReader("TestFile.txt");
However, one thing I noticed is that the TestFile is located in TestDir. If your executable is located in ProgDir as you're stating, then this will still fail because your relative path isn't right.
Try changing it to TestDir\TestFile.txt instead. IE: StreamReader sr = new StreamReader("TestDir\TestFile.txt");
The FileInfo constructor takes a single parameter of type string. Try putting quotes around TestFile.txt.
Change
FileInfo file = new FileInfo(TestFile.txt);
to
FileInfo file = new FileInfo("TestFile.txt");
Unless TestFile is an object with a property named txt of type string, in which case you have to create the object before trying to use it.
The easiest way would be to just use the file name (not the full path) and "TestDir" and give the StreamReader a relative path.
var relativePath = Path.Combine(".","TestDir",fileName);
using (var sr = new StreamReader(relativePath))
{
//...
}
I had a similar issue and resolved it by using this method:
StreamReader sr = File.OpenText(MapPath("~/your_path/filename.txt"))
This could be a good option if you need a more relative path to the file for working with different environments.
You can use path.combine to get the current directory to build and then combine the file path you need
new StreamReader(Path.Combine(Environment.CurrentDirectory, "storage"));
System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath)

How to combine two path

I have the code below and I get the result like this
C:\\Users\\Administrator\\Projects\\CA\\Libraries\\ConvertApi-DotNet\\Example\\word2pdf-console\\bin\\Release\\\\..\\..\\..\\..\\test-files\\test.docx
The file is found but I would like to show user this path and the formating is not user friendly. I would like to get
C:\\Users\\Administrator\\Projects\\CA\\Libraries\\test-files\\test.docx
I have tried to use Path.Combine but it do not work.
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string inFile = baseDirectory + #"\..\..\..\..\test-files\test.docx";
You could use a combination of Path.Combine and Path.GetFullPath:
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var file = #"..\..\..\..\test-files\test.docx";
string inFile = Path.GetFullPath(Path.Combine(baseDirectory, file));
Description
You say that the file is found.
Then you can use FileInfo (namespace System.IO) for that.
Sample
FileInfo f = new FileInfo(fileName);
f.Exists // Gets a value indicating whether a file exists.
f.DirectoryName // Gets a string representing the directory's full path.
f.FullName // Gets the full path of the directory or file.
More Information
MSDN - FileInfo Class

Categories