Reading filecontents into webbrowser control strips away my umlauts - c#

I'm using
private void infoLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string filename = "infoFiles\\Tastenkürzel.htm";
System.IO.StreamReader infoFile = new System.IO.StreamReader(filename);
string page = infoFile.ReadToEnd();
frmInfo infoForm = new frmInfo(page);
infoForm.Show();
}
to open an html file containing umlauts. When I open the file in a browser, it shows all the dots above letters I want it to, however, once I open the filecontents in the webbrowser control, the umlauts are replaced by little boxes.
Thanks in advance!

Solving the problem required adding an Encoding parameter.
System.IO.StreamReader infoFile = new System.IO.StreamReader(filename, Encoding.UTF8);

Related

Unable to replace string from text file [duplicate]

This question already has answers here:
How to find and replace text in a file
(7 answers)
Closed 4 years ago.
The code I'm trying to write is to replace a string of words within a text file. Though I'm able to read the file's content to console, I'm unable to replace the string of words and write a new string to the file.
Here's my code:
private static void filesys_created (object sender, FileSystemEventArgs e)
{
using (StreamReader sr = new StreamReader(e.FullPath))
{
Console.WriteLine(sr.ReadToEnd());
File.ReadAllText(e.FullPath);
sr.Close();
}
using (StreamWriter sw = new StreamWriter(e.FullPath))
{
string text = e.FullPath.Replace("The words I want to replace");
string newtext = "text I want it to be replaced with";
sw.Write(e.FullPath, text);
sw.Write(newtext);
sw.Close();
}
}
The problem is that the .Replace is deleting everything in the text file and only inserting the path of the directory.
Well, the problems as I see it are a) you're reading the file but not assigning the text to a variable b) you're not actually doing a replace and c) you are indeed writing the file name to the output.
You don't need to use streams so your code can be simplified to this:
var contents = File.ReadAllText(e.FullPath);
contents = contents.Replace(text, newText);
File.WriteAllText(e.FullPath, contents);
It looks like you're using a FileSystemWatcher to pick up the file, so just noting that this will fire (at least) a Changed event.
You are writing the FullPath into the file, try this:
var text = null;
using (StreamReader sr = new StreamReader(e.FullPath))
{
text = sr.ReadToEnd();
Console.WriteLine(text);
}
using (StreamWriter sw = new StreamWriter(e.FullPath))
{
var replaced = text.Replace("The words I want to replace", "text I want it to be replaced with");
sw.Write(replaced);
}

Sending Swedish and Chinese signs to Docx using OpenXML and RTF

Goal
Passing Swedish and Chinese signs to a DocX-file in a RTF format.[2]
Description
I need to dynamically generate a RTF-formatted string containing Swedish and Chinese signs and send it to an existing Docx-file. I have managed to handle the Swedish diaereses (åäö) but I can't manage to get the Chinese signs to be shown properly, instead they are shown as ????
private void buttonSendDiaeresesToDocx_Click(object sender, EventArgs e)
{
var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var filename = #"SpecialCharactersInDocx.docx";
var filepath = Path.Combine(desktop, filename);
//Dynamic content fetched from the database.
var content = "This should be Swedish and Chinese signs -> åäö - 部件名称";
var rtfEncodedString = new StringBuilder();
rtfEncodedString.Append(#"{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard ");
rtfEncodedString.Append(content);
rtfEncodedString.Append(#"\par}");
removeExistingFile(filepath);
createEmptyDocx(filepath);
addRtfToWordDocument(filepath, rtfEncodedString.ToString());
openDocx(filepath);
}
private void addRtfToWordDocument(string filepath, string rtfEncodedString)
{
//Implemented as suggested at
//http://stackoverflow.com/a/14861397/1997617
using (WordprocessingDocument doc = WordprocessingDocument.Open(filepath, true))
{
string altChunkId = "AltChunkId1";
MainDocumentPart mainDocPart = doc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainDocPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.Rtf, altChunkId);
using (MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(rtfEncodedString)))
{
chunk.FeedData(ms);
}
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
mainDocPart.Document.Body.ReplaceChild(
altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last());
mainDocPart.Document.Save();
}
}
I have tried to use different encodings for the memory stream (Default, ASCII, UTF8, GB18030, ...) but none seams to work. I've also tried to convert the encoding of the rtfEncodedString variable before passing it to the addRtfToWordDocument method.
How do I make both the Swedish and the Chinese signs to show properly in the document?
Notes and references
The above code snippet is the part of my solution that I think is relevant for the question. The entire code sample can be downloaded at http://www.bjornlarsson.se/externals/SpecialCharactersInDocx02.zip
The RTF format is needed in the real world application since the content is to be shown as a table (with bold text) in the document.
You could use wordpad to create the rtf string for you. Open wordpad copy your content save to file. And then use a texteditor to read the rtf.
your rtf string then looks like this :
{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1031{\fonttbl{\f0\fnil Consolas;}{\f1\fnil\fcharset0 Consolas;}{\f2\fnil\fcharset134 SimSun;}{\f3\fnil\fcharset0 Calibri;}}
{\*\generator Riched20 10.0.10586}\viewkind4\uc1
\pard\sa200\sl276\slmult1\f0\fs19\lang7 This should be Swedish and Chinese signs -> \f1\'e5\'e4\'f6 - \f2\'b2\'bf\'bc\'fe\'c3\'fb\'b3\'c6\f3\fs22\par
}
maybe it helps.I tested the rtf string with your code and it works!
Dynamic generate rtf string via richtextbox :
private void buttonSendDiaeresesToDocx_Click(object sender, EventArgs e)
{
var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var filename = #"SpecialCharactersInDocx.docx";
var filepath = Path.Combine(desktop, filename);
removeExistingFile(filepath);
createEmptyDocx(filepath);
rtfEncodedString = new StringBuilder();
string contentOriginal = "This should be Swedish and Chinese signs -> åäö - 部件名称";
string rtfStart =
"{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1031{\\fonttbl{\\f0\\fnil\\fcharset0 Microsoft Sans Serif;}{\\f1\\fmodern\\fprq6\\fcharset134 SimSun;}}\r\n\\viewkind4\\uc1\\pard\\f0\\fs17 ";
RichTextBox rtfBox = new RichTextBox {Text = contentOriginal};
string content = rtfBox.Rtf;
content = content.Replace(rtfStart, "");
rtfEncodedString.Append(rtfStart);
rtfEncodedString.Append(content);
rtfEncodedString.Append(#"\par}");
addRtfToWordDocument(filepath, rtfEncodedString.ToString());
openDocx(filepath);
}

Cannot access LocalFolder files on Windows phone app (UnauthorizedAccessException)

I am trying to get an application to write (then read) a simple text file in Windows Phone 8. My app has three controls: a create file button, a display file button, and a textbox where the contents are supposed to display.
I have the following events set up in my code:
private async void btnCreateFile_Click(object sender, RoutedEventArgs e)
{
await ApplicationData.Current.LocalFolder.CreateFileAsync("myFile.txt");
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("myFile.txt");
StreamWriter writer = new StreamWriter(await file.OpenStreamForWriteAsync());
writer.WriteLine("Hello World");
writer.WriteLine("Goodbye world");
}
private async void btnShowFile_Click(object sender, RoutedEventArgs e)
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("myFile.txt");
StreamReader reader = new StreamReader(await file.OpenStreamForReadAsync());
string text = reader.ReadToEnd();
text1.Text = text;
}
}
The application is throwing UnauthorizedAccessException when the StreamReader is being created. Can anyone shed any light on why?
I guess you're not disposing the StreamWriter. See the example on MSDN.
using( var writer = new StreamWriter(await file.OpenStreamForWriteAsync()))
{
writer.WriteLine("Hello World");
writer.WriteLine("Goodbye world");
}
That's why your can't read the file, because it's already taken by SreamWriter.
Always use 'using' statement when using an object that inherits from IDisposable.
You are trying to write to an already opened file and this gives you UnauthoritedException.
Try using your code block inside of using.Check out this question to find more about StreamWriter :
how to use StreamWriter class properly?

Attempting to create string from a file

Currently trying to create a string from a text file, however their seems to be an error preventing the stream reader from reading the text file correctly.
private string testString = "Cheese";
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() != DialogResult.Cancel)
{
fileName = openFileDialog.FileName;
LoadFile();
}
}
private void LoadFile()
{
String lineFromFile = "Chicken";
*StringBuilder RawFileInput = new StringBuilder();
using (StreamReader reader = new StreamReader(fileName))
{
while ((lineFromFile = reader.ReadLine()) != null)
{
RawFileInput.AppendLine(lineFromFile);
}
}*
testString = lineFromFile;
testTB.Text = testString;
}
The output should the code execute has the output textbox be empty, however should the block of code between the asterisks be commented out, the output textbox obviously displays the test phrase of Chicken. As such I'm pretty sure there is a problem with this particular block, however I can't seem to figure out what.
Thanks in advance.
If I understood well your code, you are trying to set the testTB.Text with the text in your file. Taking that in account, shouldn't your last lines be:
testString = RawFileInput.ToString();
testTB.Text = testString;
You can achieve the same result with no need of a StringBuilder, replacing your whole LoadFile method with this line:
testTB.Text = File.ReadAllText(fileName);
You should be able to read a document in entirety, like the following:
var builder = new StringBuilder();
using(var reader = new StreamReader(path))
builder.Append(reader.ReadToEnd());
That would be the ideal, as it is more performant than ReadAllText.
ReadToEnd works best when you need to read all the input from the
current position to the end of the stream. If more control is needed
over how many characters are read from the stream, use the
Read(Char[], Int32, Int32) method overload, which generally results in
better performance. ReadToEnd assumes that the stream knows when it
has reached an end. For interactive protocols in which the server
sends data only when you ask for it and does not close the connection,
ReadToEnd might block indefinitely because it does not reach an end,
and should be avoided.
If you're wanting the contents of a file to populate a textbox, just set the Multiline property to true, and use File.ReadAllLines()
testTb.Lines = File.ReadAllLines(fileName);

How to open txt file on localhost and change is content

i want to open a css file using C# 4.5 and change only one file at a time.
Doing it like this gives me the exception - URI formats are not supported.
What is the most effective way to do it ?
Can I find the line and replace it without reading the whole file ?
Can the line that I am looking and than start to insert text until
cursor is pointing on some char ?
public void ChangeColor()
{
string text = File.ReadAllText("http://localhost:8080/game/Css/style.css");
text = text.Replace("class='replace'", "new value");
File.WriteAllText("D://p.htm", text);
}
I believe File.ReadAllText is expecting a file path, not a URL.
No, you cannot search/replace sections of a text file without reading and re-writing the whole file. It's just a text file, not a database.
most effective way to do it is to declare any control you want to alter the css of as "runat=server" and then modify the CssClass property of it. There is no known alternative way to modify the css file directly. Any other hacks is just that.. a hack and very innefficient way to do it.
As mentioned before File.ReadAllText does not support url. Following is a working example with WebRequest:
{
Uri uri = new Uri("http://localhost:8080/game/Css/style.css");
WebRequest req = WebRequest.Create(uri);
WebResponse web = req.GetResponse();
Stream stream = web.GetResponseStream();
string content = string.Empty;
using (StreamReader sr = new StreamReader(stream))
{
content = sr.ReadToEnd();
}
content.Replace("class='replace'", "new value");
using (StreamWriter sw = new StreamWriter("D://p.htm"))
{
sw.Write(content);
sw.Flush();
}
}

Categories

Resources