Unable to read textfile with special characters from a directory - c#

I'm trying to read a textfile name with special characters(Ex: Student_*_Details.txt) from a directory. When I try to read them it says it has illegal characters in the path as the textfile name has these special characters and unable to read the file.
Code:
using (StreamReader streamReader = new StreamReader(#"\\NKR1009FHN\Student_*_Details.txt"))
I' have used the below set of codes to remove the illegal characters from the filename. But in the streamReader if fails as the special characters are getting replaced and unable to find the file since the actual filename got changed due to the below method used.
private static string GetValidFileName(string fileName)
{
String ret = Regex.Replace(fileName.Trim(), "[^A-Za-z0-9_. ]+", "")
return ret.Replace(" ", String.Empty);
}
Is there any workaround to get this fixed?
Really appreciate suggestions.

Related

File name with special characters( å, ä, ö ) are unable to read by ionic.zip

I'm trying to read filename with Swedish characters. When the files are being read I get the exception file not found. The same work for file names without special characters.
I tried with different encoding but still the file names was not being read. Is there a way to handle this
Im running the code on Windows 10.
using (var zip = new ZipFile())
{
zip.AlternateEncoding = Encoding.UTF8;
zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.Always;
zip.UseUnicodeAsNecessary = true;
string filepath = #"C:\Users\username\rel\Reådmeö.txt";
zip.AddItem(filepath, Path.GetFileName(filepath));
zip.Save(zipFileSavePath);
}
following is the error
System.IO.FileNotFoundException: 'That file or directory (C:\Users\username\rel\Reådmeö.txt) does not exist!'

How to read the text from another computer

I have tried to read the file from other computer using the IP address, but i could not able to read that one.It's raised the exception like "Could not find a part of the path 'E:\IPFile_Read\IPFile_Read\bin\Debug\#\IPAddress\Test\News.txt'"
Code:
{
StreamReader sr = new StreamReader("#\\IPaddress\\Test\\News.txt");
line = sr.ReadLine();
while (line != null)
{
text_Data.Text = line;
line = sr.ReadLine();
}
sr.Close();
Console.ReadLine();
}
How can i read the text file from another computer.
"#\\IPaddress\\Test\\News.txt" should be #"\\IPaddress\Test\News.txt". For verbatim strings, the # goes before the opening quote, and if you're using a verbatim string, you don't need to escape the slashes. The UNC prefix still needs the \\, because it really does have two backslashes.

Creating files using c#, like an evernote

I currently am making a UI for a note keeper and was just going to preview documents etc, but i was wondering what file type i would need to create if instead i wanted to do things like tag the file etc, preferably in c#, basically make my own evernote, how do these programs store the notes?
I dont know how to directly tag the file, but you could create your own system to do it. I mentioned two ways to do it:
The first way is to format the note's / file's contents so that there are two parts, the tags and the actual text. When the program loads the note / file, it seperates the tags and the text. This has the downside that the program have to load the whole file to just find the tags.
The second way is to have a database with the filename and it's associated tags. In this way the program doesn't have to load the whole file just to find the tags.
The first way
In this solution you need to format your files in a specific way
<Tags>
tag1,tag2,tag3
</Tags>
<Text>
The text you
want in here
</Text>
By setting up the file like this, the program can separate the tags from the text. To load it's tags you'd need this code:
public List<string> GetTags(string filePath)
{
string fileContents;
// read the file if it exists
if (File.Exists(filePath))
fileContents = File.ReadAllText(filePath);
else
return null;
// Find the place where "</Tags>" is located
int tagEnd = fileContents.IndexOf("</Tags>");
// Get the tags
string tagString = fileContents.Substring(6, tagEnd - 6).Replace(Environment.NewLine, ""); // 6 comes from the length of "<Tags>"
return tagString.Split(',').ToList();
}
Then to get the text you'd need this:
public string GetText(string filePath)
{
string fileContents;
// read the file if it exists
if (File.Exists(filePath))
fileContents = File.ReadAllText(filePath);
else
return null;
// Find the place where the text content begins
int textStart = fileContents.IndexOf("<Text>") + 6 + Environment.NewLine.Length; // The length on newLine is neccecary because the line shift after "<Text>" shall NOT be included in the text content
// Find the place where the text content ends
int textEnd = fileContents.LastIndexOf("</Text>");
return fileContents.Substring(textStart, textEnd - textStart - Environment.NewLine.Length); // The length again to NOT include a line shift added earlier by code
}
Then I'll let you find out how you do the rest.
The second way
In this solution you have a database file over all your files and their associated tags. This database file would look like this:
[filename]:[tags]
file.txt:tag1, tag2, tag3
file2.txt:tag4, tag5, tag6
The program will then read the file name and the tags in this way:
public static void LoadDatabase(string databasePath)
{
string[] fileContents;
// End process if database doesn't exist
if (File.Exists(databasePath))
return;
fileContents = File.ReadAllLines(databasePath); // Read all lines seperately and put them into an array
foreach (string str in fileContents)
{
string fileName = str.Split(':')[0]; // Get the filename
string tags = str.Split(':')[1]; // Get the tags
// Do what you must with the information
}
}
I hope this helps.

Removing char hex codes from string

I have a folder named Folderć, which contains smth.jpg. As folder has letter ć in name, filepath is saved in database as Folder%C0%01%/smth.jpg.
Letter ć is saved as Hex code. This is not a problem while previewing image on website.
Problem happens when i am trying to make a subfolder in Folderć via C# function. Function gets filepath string, finds folder name and creates subfolder in it. As my string contains hex code instead of letter ć function cant find that path thus cant create subfolder.
That string is in UTF-8 format, so changing the encoding doesnt change anything.
Anyone knows where is problem and how to solve it?
You can encode the name with Base64:
public string ToBase64String(string text)
{
byte[] data = Encoding.UTF8.GetBytes(text);
return Convert.ToBase64String(data);
}
and use it string myEncFolderPath = ToBase64String(myFolderPath); before saving the string in the DB.
After you receive the string from the DB, you can decode it back to a normal string with:
public string FromBase64String(string base64)
{
byte[] data = Convert.FromBase64String(base64);
return Encoding.UTF8.GetString(data);
}
by using string myFolderPath = FromBase64String(myEncFolderPath);.
That way, you can save strings freely in the DB.

why wont XML read from string? (but will from .txt of same data)

this is the code in question:
using (var file = MemoryMappedFile.OpenExisting("AIDA64_SensorValues"))
{
using (var readerz = file.CreateViewAccessor(0, 0))
{
var bytes = new byte[567];
var encoding = Encoding.ASCII;
readerz.ReadArray<byte>(0, bytes, 0, bytes.Length);
File.WriteAllText("C:\\myFile.txt", encoding.GetString(bytes));
var readerSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
using (var reader = XmlReader.Create("C:\\myFile.txt", readerSettings))
{
This is what myfile.txt looks like:
<sys><id>SCPUCLK</id><label>CPU Clock</label><value>1598</value></sys><sys><id>SCPUFSB</id><label>CPU FSB</label><value>266</value></sys><sys><id>SMEMSPEED</id><label>Memory Speed</label><value>DDR2-667</value></sys><sys><id>SFREEMEM</id><label>Free Memory</label><value>415</value></sys><sys><id>SGPU1CLK</id><label>GPU Clock</label><value>562</value></sys><sys><id>SFREELVMEM</id><label>Free Local Video Memory</label><value>229</value></sys><temp><id>TCPU</id><label>CPU</label><value>42</value></temp><temp><id>TGPU1</id><label>GPU</label><value>58</value></temp>
if i write the data to a txt file on the hard drive with:
File.WriteAllText("C:\\myFile.txt", encoding.GetString(bytes));
then read that same text file with the fragment XmlReader:
XmlReader.Create("C:\\myFile.txt");
it reads it just fine, the program runs and completes like it supposed to, but then if i directly read with the fragment XmlReader like:
XmlReader.Create(encoding.GetString(bytes));
I get exception when run " illegal characters in path" on the XmlReader.Create line.
ive tried writing it to a separate string first and reading that with xmlreader, and it wouldn't help to try to print it to CMD to see what it looks like because CMD wouldnt show the invalid characters im dealing with right?
but oh well i did Console.WriteLine(encoding.GetString(bytes)); and it precisely matched the txt file.
so somehow writing it to the text file is removing some "illegal characters"? what do you guys think?
XmlReader.Create(encoding.GetString(bytes));
XmlReader.Create() interprets your string as the URI where it should read a file from. Instead encapsulate your bytes in a StringReader:
StringReader sr = new StringReader(encoding.GetString(bytes));
XmlReader.Create(sr);
Here:
XmlReader.Create(encoding.GetString(bytes));
you are simply invoking the following method which takes a string representing a filename. However you are passing the actual XML string to it which obviously is an invalid filename.
If you want to load the reader from a buffer you could use a stream:
byte[] bytes = ... represents the XML bytes
using (var stream = new MemoryStream(bytes))
using (var reader = XmlReader.Create(stream))
{
...
}
The method XmlReader.Create() with a single string as argument needs a URI passed and not the XML document as string, please refer to the MSDN. It tries to open a file named "<..." which is an invalid URI. You can pass a Stream instead.
You are passing the xml content in the place where it is expecting a path, as evidenced by the error - illegal characters in path
Use an appropriate overload, and pass a stream - http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.create.aspx

Categories