How to fix "Illegal characters in path." in file path? - c#

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

Related

How to delete the last character of a file with C#

Hello I'm beginner with C# and I want to delete the last character of my file to inject JSON objects to this file manually (I know that's not the best way to do that), so I can get the right format I tried with multiple ways like open the file, manipulating the string (deleting the last character) and when I try to replace the text in that same file I have errors like IOException: The process cannot access the file 'file path' because it is being used by another process or System.UnauthorizedAccessException : 'Access to the path 'C:\Users\ASUS\Desktop\Root' is denied.
I'll show you the code :
StoreLogs Log = new StoreLogs()
{
Id = ID,
DateTime = dateT,
TaskName = task,
SrcAddress = srcPath,
DstAddress = path,
FileSize = DirSize(new DirectoryInfo(srcPath)),
DelayTransfer = ts.Milliseconds,
};
// Record JSON data in the variable
string strResultJson = JsonConvert.SerializeObject(Log);
// Show the JSON Data
// Console.WriteLine(strResultJson);
// Write JSON Data in another file
string MyJSON = null;
string strPath = #"C:\Users\ASUS\Desktop\Backup\logs\log.json";
if (File.Exists(strPath))
{
//FileInfo table = new FileInfo(strPath);
//string strTable = table.OpenText().ReadToEnd();
//string erase = strTable.Remove(strTable.LastIndexOf(']'));
//Console.WriteLine(erase);
//StreamReader r1 = new StreamReader(strPath);
//string strTable = r1.OpenText().ReadToEnd();
//string erase = strTable.Remove(strTable.LastIndexOf(']'));
//r1.Close();
using (StreamReader sr = File.OpenText(strPath))
{
string table = sr.ReadToEnd();
string erase = table.Remove(table.LastIndexOf(']'));
sr.Close();
File.WriteAllText(strPath, erase);
}
//MyJSON = "," + strResultJson;
//File.AppendAllText(strPath, MyJSON + "]");
//Console.WriteLine("The file exists.");
}
else if (!File.Exists(strPath))
{
MyJSON = "[" + strResultJson + "]";
File.WriteAllText(strPath, MyJSON);
Console.WriteLine("The file doesn't exists.");
}
else
{
Console.WriteLine("Error");
}
// End
Console.WriteLine("JSON Object generated !");
Console.ReadLine();
And that's the result I want :
[{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0}]
Edit :
Thank you all for your advices
Solution:
FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.ReadWrite);
fs.SetLength(fs.Length - 1);
fs.Close();
In the code example you have posted you are opening a stream to read the file. A using block will dispose the stream after you exit the block. You are trying to write to the file, while the read stream is still accessing it (the read stream still exists). You've basically opened the file, you read from it, and are trying to write back to it while still holding it open. The reason this is a problem is that you are not using the stream to write. So your second, write, process is unable to access the file. I see you are closing the stream prior to write, but I'm willing to bet it's still holding the reference open.
I would try this method:
How to both read and write a file in C#
what it says is the access to the path (C:\Users\ASUS\Desktop\Root) denied for the user who is running the application. for ex: If you are running from Visual studio on user1 windows login then user1 should have appropriate rights to that root folder. If the code is running by itself (exe) then check the access for that user who is invoking that exe.
Based on the errors you posted seems that:
Maybe you're leaving some stream open pointing to the file you want to edit, use the 'using' statement to avoid this (see this link for more info)
You're trying to access a file when you don't have needed permissions (you aren't a system admin or file is read-only), try changing file ubication or setting it to be writeable (see this link for mor info about the UnauthorizedAccessException exception)
Hope this helps you!

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

the given path's format is not supported. c#

OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select Student Picture";
ofd.InitialDirectory = #"C:\Picture";
ofd.Filter = "All Files|*.*|JPEGs|*.jpg";
//ofd.Multiselect = false;
if (ofd.ShowDialog()==DialogResult.OK)
{
if (ofd.CheckFileExists)
{
pbStudent.ImageLocation = ofd.FileName;
string path = ofd.SafeFileName;
System.IO.File.Copy(ofd.FileName, "/Resources/SImages/" + lblRNo + ".jpg");
}
}
Can some one help me resolve issue with this error message:
the given path's format is not supported.
Here you use the correct way of formatting the path in Windows with a Backslash
ofd.InitialDirectory = #"C:\Picture";
And in the next line you divert from it
System.IO.File.Copy(ofd.FileName, "/Resources/SImages/" + lblRNo.Text + ".jpg");
just keep the way you did it in the beginning:
System.IO.File.Copy(ofd.FileName, #"\Resources\SImages\" + lblRNo.Text + ".jpg");
One way of avoiding such irritations is to use System.IO.Path.Combine()
string path = System.IO.Path.Combine("Resources", "SImages");
EDIT: due to the extraordinary observation by Steve I changed lblRNo to lblRNo.Text
Your problem is the lblRNo variable used to express the name of the destination file. It seems that this is a label of your program and not a string containing your file name. To get the correct value you should use the property Text of the label.
System.IO.File.Copy(ofd.FileName, #"/Resources/SImages/" + lblRNo.Text + ".jpg");
Of course, having specified a relative path then you should be sure that this path exists relative to the root drive where your code is executing.
For example, if your code runs on the C: drive then a path
C:\Resources\SImages
should exist otherwise you get the execption about a part of your path not being found.
As other have said, the proper path separator in Windows is the backslash but you could also use the forward slash without any problem
Try this instead:
System.IO.File.Copy(ofd.FileName, #"\Resources\SImages\" + lblRNo + ".jpg");
the / is for the internet, the \ is for inside your computer :)

MIME Attachment Names containing Extended Characters Fails

While working on a project that emails files with international filenames, I've come across an unusual issue. if I attach with a US-ASCII filename only, I can get better than 200 characters long without errors.
If I include an extended character, it encodes in UTF-8 and the length before it gets funky is very small (< 40 characters). To define funky.. here's an example filename after it goes bad:
=utf-8BSU5GT1JNw4FUSUNBX0ltcGFjdF9Bc3Nl
it looks like UTF8 encoded string with a UTF-8 decoding instruction or a mime boundary... not sure which.
Has anyone seen this before -- and what are the rules / limitations of filenames -- I tried emailing the file by hand through outlook and it handles it, so I don't think it is a MIME specific limitation.
Sample code:
class Program
{
private const string DOMAIN = "foobar.com";
private const string SMTPHOST = "mail." + DOMAIN;
private const string FROM = "chadwick.posey#" + DOMAIN;
private const string TO = FROM;
static void Main(string[] args)
{
MailMessage msg = new MailMessage(FROM, TO, "Subject", "Body");
string path = Path.GetTempPath();
string name = "AAAAAA_AAAAAAAAAAAA_AAAAAAA_AAAA - IIIIIII CCCCCCCCCC DD IIIIIIÁIIII_20111018_091327.pptx";
File.WriteAllText(path + "\\" + name, "blah");
Attachment att = new Attachment(path + "\\" + name, new ContentType("application/vnd.openxmlformats-officedocument.presentationml.presentation"));
msg.Attachments.Add(att);
SmtpClient client = new SmtpClient(SMTPHOST, 25);
client.Send(msg);
}
}
I've tried (so far) -- setting the encoding for the attachment.NameEncoding to UTF8 and UTF32, neither worked. Setting the ContentDisposition.FileName on the attachment fails because it is not using US-ASCII characters only.
Any suggestions on how to get it to include the full filename with the accent / extended characters in tact?
Thanks
Chadwick
There is a hotfix from microsoft that seems to have done the trick for me.
Check http://support.microsoft.com/kb/2402064
On that page, there is a download link that will get you what you need.
Just install the correct version, depending on your system.
this should work:
Attachment att = new Attachment(#"c:\path to file\somename.txt",
System.Net.Mime.MediaTypeNames.Application.Octet);
//this itself should work.
att.Name = "история-болезни.doc"; // non-english filename
//if the above line doesn't make it work, try this.
att.Name = System.Web.HttpUtility.UrlEncode(att.Name, System.Text.Encoding.UTF8);
How to set the attatchment file name with chinese characters in C# SmtpClient programming?

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