Copy file from one directory to another - c#

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);

Related

How to fix "Illegal characters in path." in file path?

I ran into an issue with writing a file path correctly to text file. I get an error "Illegal characters in path.".
My incoming file path from a function is
imagePath = "c:\temp\temp\file_name.jpg".(from a function)
Whenever I use the following
imagePath = Path.GetFullPath(imagePath);
I get the error "Illegal characters in path.".
The issue here is that "\t" is considered as an illegal character although its part of path. So how could I write this to a text file? I do not have control over such characters in the name.
How to write the full path ?
Here I am adding more details about the function.
ServerResponse jsonResult = new ServerResponse();
try
{
jsonResult = JsonConvert.DeserializeObject<ServerResponse>(strResponse);
string imagePath = jsonResult.image;
// string imagePath = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
// string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
imagePath = Path.GetFullPath(imagePath);
File.AppendAllText(PredictFileName, (string)imagePath);
txtJSONresult.AppendText((String)imagePath.ToString());
txtJSONresult.AppendText(Environment.NewLine);
}
catch (Exception ex)
{
txtJSONresult.AppendText(strResponse);
txtJSONresult.AppendText(Environment.NewLine);
txtJSONresult.AppendText(ex.Message);
txtJSONresult.AppendText(Environment.NewLine);
}
Server send the image path as "c:\temp\temp\file_name.jpg" I want to save that path to txt file in local PC. No matter I do I always have "\t" or probably other special characters that considered to be illegal.
string imagePath = jsonResult.image
So whats the right way to write this path to text file regardless of what it has?
Here is the JSON string I get from the server :
{"image":"c:\testimage\test.jpg","predictions":[[1.03891e-05, 0.0128408, 0.914102, 9.68333e-05, 0.0729495]]}
Fixing from server side
Ensure proper string formats are sent:
"C:\\doubleSlash\\paths"
#"C:\singleWith\atSymbol"
Fixing from client side and no server control
Masage data by replacing invalid characters with correct counterparts if possible, otherwise contact service provider about server side solution ;]

Ask to user the Path to export File on C# Console

I am new at programming and I'm trying to add into a string variable the path to create a txt File. However I'm not getting it right if can it be done using Replace or Concat. I have never used that on C#. Here´s what I´ve done so far:
string path = #"###";
do
{
Console.Write("Insert the path in oder to export data: ");
string temp = Console.ReadLine();
}
while (String.IsNullOrEmpty(path));
path = path.Replace("###", "temp");
The following line
path = path.Replace("###", "temp");
replaces the part ### in the path with the literal string temp.
At the end of the operation, contents of your path variable will be "temp".
You don't really need to do a Replace at all. Instead,
string path = string.Empty;
do
{
Console.Write("Insert the path in oder to export data: ");
path = Console.ReadLine();
}
while (String.IsNullOrEmpty(path));
will assign the user entered path into your path variable.

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.

C# trim application path

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""";

Having Trouble Renaming Files that Match with my RegEx

I have an app that "cleans" "dirty" filenames. "Dirty" filenames have #%&~+{} in their filenames. What my app does is see if they are a match for a RegEx pattern i have defined and then send it to a method called FileCleanUp where it "cleans" the file and replaces invalid chars with a "". However, i noticed while i was running this, that my FileCleanup method only works on SOME files and not others!
Here is my code:
public class SanitizeFileNames
{
public void FileCleanup(List<string>paths)
{
string regPattern = (#"[~#&!%+{}]+");
string replacement = "";
Regex regExPattern = new Regex(regPattern);
foreach (string files2 in paths)
try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
//write to streamwriter
System.IO.File.Move(files2, sanitized);
}
catch (Exception e)
{
//write to streamwriter
}
}
I tested on a few files with the names like: ~Test.txt, #Test.txt, +Text.txt, Test&Test.txt, T{e}st.txt, Test%.txt.
The ones i could not get to be renamed were: ~Test.txt, +Test.txt, T{e}st.txt
I debugged this and weirdly enough, it shows that these files that did not get renamed for some reason as correct on the debugger. Instead of showing ~Test.txt as a "sanitized" file name, it was Text.txt. So on the app side, it DOES read my foreach loop correctly.
However, i'm really stumped as to why it's not actually renaming these files. Anybody have a clue as to why this might be? Does it have to do with the File.Move() ?
EDIT: On further testing, i realize that it also doesn't rename files that are like this: ~~test.txt or ##test.txt
You have an empty catch block. Why don't you print out the exception message to see what's happening?
My guess is that the file names are matching the regex, but you're unable to rename the files because a file named Test.txt already exists after #Test.txt is renamed to that. Try renaming the other files to ~Test2.txt, +Test3.txt, T{e}st4.txt before running the program again.

Categories

Resources