C# trim application path - c#

I have this application path:
C:\Documents and Settings\david\My Documents\app\
And a file path:
C:\Documents and Settings\david\My Documents\app\stuff\file.txt
How can I trim the application path from the file path so it becomes stuff\file.txt? Reason being one of the command line tools I'm using doesn't support spaces in the file path.

Try this:
Uri path = new Uri(#"C:\Documents and Settings\david\My Documents\app\stuff\file.txt");
Uri workingDirectory = new Uri(Directory.GetCurrentDirectory());
string relativePath = workingDirectory.MakeRelativeUri(path).ToString();
Related documentation:
Uri.MakeRelativeUri
Directory.GetCurrentDirectory

i don't know which command tool you are using, but normally they work if we enclosed the string/ path in quotation marks like this
"C:\Documents and Settings\david\My Documents\app\stuff\file.txt"

Not sure why normal string replace won't do:
string filePath = #"C:\Documents and Settings\david\My Documents\app\stuff\file.txt";
string appPath = #"C:\Documents and Settings\david\My Documents\app\";
string trimmed = filePath.Replace(appPath, "");
However, if you simply enclose the full path in quotes ("), most command line tools will be fine with spaces:
string escapedPath = #"""C:\Documents and Settings\david\My Documents\app\stuff\file.txt""";

Related

Copy file from one directory to another

I am pretty new to C# and I am trying to get my program to copy a file from one location to another. The method I have is as below;
private void CopyInstallFiles(object sender, EventArgs e)
{
string sourceFile = "F:\\inetpub\ftproot\test.txt";
string copyPathone = directoryImput.Text;
System.IO.File.Copy(sourceFile, copyPathone);
}
As you can is there is a fixed source location however the destination is taken from user input (text box). The problem I have however, is that when I try to copy to a location for example C:\testfolder. I get an illegal character exception.
Look at your sourceFile string and be aware of using the \, which could be interpreted as escape character.
To prevent this start your string with #
string sourceFile = #"F:\inetpub\ftproot\test.txt";
or
string sourceFile = "F:\\inetpub\\ftproot\\test.txt";
File.Copy requires the full filename for the destination.
destFileName
Type: System.String
The name of the destination file. This cannot be a directory.
If your input is just the folder name then you need to add the filename of the source file.
private void CopyInstallFiles(object sender, EventArgs e)
{
// The correct syntax for a path name requires the verbatim # char
string sourceFile = #"F:\inetpub\ftproot\test.txt";
string file = Path.GetFileName(sourceFile);
string copyPathone = directoryImput.Text;
System.IO.File.Copy(sourceFile, Path.Combine(copyPathone, file), true);
}
Note the final parameter = true to overwrite a file in the destination folder.
As a side note, I suggest you to remove the textbox as input for a folder name but instead use the FolderBrowserDialog
Try this :
string path = #"C:\Program Files (x86)\your\path\main.txt";
This is because in C# (and C++ and C and some other languages) string can contain special characters. Those characters are followed by '\'. So for example string:
"\n"
Will not show you \n This is special character called - new line. So, when you create path like that:
"C:\Dir\file.txt"
C# expects that there are two special characters: \D and \f. But there is no special characters like that. Thus the error.
To put character '\' into string you have to double it, so:
"\\n"
would output \n
The same is with paths: "C:\Dir\file.txt"
C# has an alternative. You can have single '\' in path, but such a string must be followed by at sign (#):
string properPath = #"C:\dir\file.txt";
string properPath2 = "C:\\dir\\file.txt";
string error = "C:\dir\file.txt"
Either FIle.Copy
Move it to new location like below
new_file_path = file_path.Replace(".xls", " created on " + File.GetLastWriteTime(file_path).ToString("dd-MM-yyyy hh-mm-ss tt") + ".xls");
File.Move(file_path, new_file_path);
File.Delete(file_path);

How to move a file that has no file extension? C#

if (File.Exists(#"C:\\Users" + Environment.UserName + "\\Desktop\\test"))
{ /\
this file has no file extension
}
The file test has no extension and I need help to either move or rename this file to something with a extension
Having no extension has no bearing on the function.
Also, a rename is really just a move "in disguise", so what you want to do is
File.Move(#"C:\Users\Username\Desktop\test", #"C:\Users\Username\Desktop\potato.txt")
Please bear in mind the # before the string, as you haven't escaped the backslashes.
There's nothing special about extensionless files. Your code is broken because you use string concatenation to build a path and you're mixing verbatim and regular string literal syntax. Use the proper framework method for this: Path.Combine().
string fullPath = Path.Combine(#"C:\Users", Environment.UserName, #"Desktop\test");
if(File.Exists(fullPath))
{
}
You also should use the proper framework method to get the desktop path for the current user, see How to get a path to the desktop for current user in C#?:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fullPath = Path.Combine(desktopPath, "test");
Then you can call File.Move() to rename the file, see Rename a file in C#:
if(File.Exists(fullPath))
{
string newPath = fullPath + ".txt";
File.Move(fullPath, newPath);
}
You can get all files without extension in this way:
var files = Directory.EnumerateFiles(#"C:\Users\Username\Desktop\")
.Where(fn => string.IsNullOrEmpty(Path.GetExtension(fn)));
Now you can loop them and change the extension:
foreach (string filePath in filPaths)
{
string fileWithNewExtension = Path.ChangeExtension(filePath, ".txt");
string newPath = Path.Combine(Path.GetDirectoryName(filePath), fileWithNewExtension);
File.Move(filePath, newPath);
}
As you can see, the Path-class is a great help.
Update: if you just want to change the extension of a single file that you already know it seems that Dasanko has already given the answer.

Issue in File path

In my project there is a folder and in that folder there is text file. I want to read that text file
string FORM_Path = #"C:\Users\...\Desktop\FormData\Login.txt";
bool first = true;
string line;
try
{
using (StreamReader streamReader = File.OpenText(FORM_Path))
{
line = streamReader.ReadLine();
}
}
but I always get an error - file does not exist. how can i solve the problem in the path of text file.
Make sure your file's properties are set to copy the file to output directory. Then you can use the following line to get full path of your text file:
string FilePath = System.IO.Path.Combine(Application.StartupPath, "FormData\Login.txt");
You path is not in correct format. Use #".\FormData\Login.txt" instead of what you have
You are trying to give relative path instead of physical path. If you can use asp.net use Server.MapPath
string FORM_Path = Server.MapPath("~/FormData/Login.txt");
If the text file is in execution folder then you can use AppDomain.BaseDirectory
string FORM_Path = AppDomain.CurrentDomain.BaseDirectory + "FormData\\Login.txt";
If it is not possible to use some base path then you can give complete path.
Avoid using relative paths. Instead consider using the methods in the Path class.
Path.Combine
Path.GetDirectoryName
Step 1: get absolute path of the executable
var path = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
Step 2: get the working dir
var dir = Path.GetDirectoryName(path);
Step 3: build the new path
var filePath = Path.Combine(dir , #"FormData\Login.txt");

directory path as string: ensure DirectoryPathSeperator at the end of the string

Is there a method in .NET, which automatically appends a backslash at the end of a path which is a string?
Something like:
var path = #"C:\Windows";
path = Path.GetPathWithSeperatorAtTheEnd(path);
Console.WriteLine(path);
// outputs C:\Windows\
What I currently do is:
if (!path.EndsWith(#"\")) path += #"\";
EDIT: What I'd like to achieve is, that if I append filenames to a path I don't need to worry about, that something like this happens. Or is there another approach than appending path and filename?
var fullFilename = path + filename;
// path : C:\Windows
// filename: MyFile.txt
// result : C:\WindowsMyFile.txt
You can use: System.IO.Path.Combine
Example:
var path = #"C:\Windows";
path = Path.Combine(path, "win.ini");
// path is #"C:\Windows\win.ini"

C# Bilingual Directory Separator Character for Non-English Windows

I am trying to create-read/write a file into a subfolder of the users AppData\Roaming folder:
string fileloc = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FolderName" + Path.AltDirectorySeparatorChar + "SomeFile.txt");
This is working brilliantly on my computer, but when I ran the program on a friend's Japanese laptop (which uses ¥ as its directory separator) they were only able to read/write to the file, and the program would crash if it needed to create the file. (I also tried the non-Alt directory separator.)
The string fileloc printed:
C:¥Users¥UserName¥Appdata¥Roaming¥FolderName/SomeFile.txt
How about
string fileloc = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FolderName"), "SomeFile.txt");
Or, perhaps easier to comprehend:
string directoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FolderName");
string fileloc = Path.Combine(directoryPath, "SomeFile.txt");
string fileloc = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.Combine("FolderName", + "SomeFile.txt"));
should do what you are expecting. Does that work for you?

Categories

Resources