How to combine two path - c#

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

Related

Get the filename of a file that was created through ZipFile.ExtractToDirectory()

string zipPath = #"D:\books\"+fileinfo.DccFileName;
string extractPath = #"D:\books";
System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
This is a simple piece of code that does exactly what i want it to do: Gets a zip file from d:\books and unzips it into the same directory. Is there any way i can read the filename of the newly created file (considering that there is only one file in the .zip archive). I would prefer a solution that does not involve reading changes in the directory since other files might be created in it at the same time of the unzip.
You can construct the path by inspecting the archive
var intentedPath = string.Empty;
//open archive
using (var archive = ZipFile.OpenRead(zipPath)) {
//since there is only one entry grab the first
var entry = archive.Entries.First();
//the relative path of the entry in the zip archive
var fileName = entry.FullName;
//intended path once extracted would be
intentedPath = Path.Combine(extractPath, fileName);
}

Regex to get whatever the parent directory of my file is in string file path

I have a string file path and I am looking to get the name of the folder that is next up from the file.
Here is my file path:
Test/FilePathNeeded/testing.txt
I am sure there is a way to get FilePathNeeded from the file path above with regex, I just am not sure how it would be done. My thought is that the amount of directories that testing.txt is in should not matter, but the folder needed would always be one up from the file.
I hope this makes sense. Please let me know if it doesn't. Would anyone be able to help?
Without Regex, You can use:
string directory = new DirectoryInfo(
Path.GetDirectoryName("Test/FilePathNeeded/testing.txt")
).Name;
Path.GetDirectoryName will return Test/FilePathNeeded that you can use in the constructor of DirectoryInfo and get Name.
Another option is to use Directory.GetParent like:
var directory = Directory.GetParent("Test/FilePathNeeded/testing.txt").Name;
Simply use:
var dir = new FileInfo("Test/FilePathNeeded/testing.txt").Directory.Name;
This will return FilePathNeeded
Use the FileInfo class:
var fileInfo = new FileInfo(#"Test/FilePathNeeded/testing.txt");
var directoryInfo = fileInfo.Directory;
var parentDirectoryName = directoryInfo.Name;

Create a copy of a file in same location as original

The end-user supplies a path, indicating where the original document is.
string DocxFileName = "C:\\WorksArshad\\3.docx";
I'd like to create a copy of the document name 3.docx as 3Version1.docx and store the copy in the same directory as the original.
How do I get the whole path without the file name and extension?
(i.e.) I need to get the "C:\\WorksArshad\\" path alone.
FileInfo file = new FileInfo(Session.FileName);
string path = file.Directory.tostring();
and then using
string fileName = Path.GetFileNameWithoutExtension(Session.FileName);
string DocxFileNamee = path + "\\" + fileName + "V1.docx";
File.Copy(Session.FileName, DocxFileNamee, true);
where in Session.FileName = "C:\WorksArshad\3.docx" and in path I'd get "C:\WorksArshad"
requirement solved .
Or
File.Copy(Session.FileName, Path.Combine(Path.GetDirectoryName(Session.FileName)
, Path.GetFileNameWithoutExtension(Session.FileName)+"V1.docx"),true);
both the above gives the solution

C# absolute path with streamReader

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.

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)

Categories