I have problem with RichTextBox in C#.
When I try load to RichTextBox text like "C:\Users\adasal\Desktop\raporty_handel\rpt\rtf\bruegman.rtf" from .rtf file I gettingn something like "C:_handel.rtf"
This code is write in Active Reports console.
My code:
string resoult = "C:\\Users\\adasal\\Desktop\\raporty_handel\\rpt\\rtf\\bruegman.rtf"
System.IO.FileStream rtfCreate = System.IO.File.Create(resoult);
System.Byte[] info = new System.Text.UTF8Encoding(true).GetBytes(resoult);
rtfCreate.Write(info, 0, info.Length);
rtfCreate.Close();
System.IO.FileStream streamRTF = new System.IO.FileStream(resoult,
System.IO.FileMode.Open, System.IO.FileAccess.Read);
this.RichTextBox1.Load(streamRTF, RichTextType.Rtf);
Someone can help? I want to show whole path on report.
You have to escape '\' characters which have special meaning in RTF.
For example:
public void ActiveReport_ReportStart()
{
string resoult = "C:\\Users\\adasal\\Desktop\\raporty_handel\\rpt\\rtf\\bruegman.rtf";
this.RichTextBox1.RTF = resoult.Replace("\\", "\\\\");
}
Related
I have a hindi RTF file with content like:
कोलकाता, 11 दिसंबर पश्चिम बंगाल के बर्दवान जिले में कक्षा नौ की एक छात्रा ने फांसी लगाकर आत्महत्या कर ली।
In my console application I want to read that RTF file and Change some content programatically.
I using streamreader to read the file but when converting to string it is producing the following output:
ÚUæCþUèØ-SßæS‰Ø
×Âý Ñ Sßæ§Ù Üê •¤è ¼ßæ ÂØæü# ×æ˜æ ×ð´ ãUôÙð •¤æ ¼æßæ
ÖæðÂæÜ, vv ç¼â¢ÕÚ (¥æ§ü°°Ù°â)Ð ×ŠØ Âý¼ðàæ ×ð´ Sßæ§Ù Üê ¥æñÚ ÇðU¢»ê âð ¥Õ Ì•¤ •¤§ü Üæð»æð´ •¤è ×æñÌ ãUæð ¿é•¤è ãñU ¥õÚU ¥SÂÌæÜ ×ð´ ç¿ç•¤ˆâ•¤èØ âéçßÏæ¥ô´ •¤è •¤×è •ð¤ âæÍ-âæÍ ¼ßæ¥ô´ •ð¤ ¥Öæß •ð¤ Öè ¥æÚUæð ܻÌð ÚãðU ãñU¢Ð
SßæS‰Ø çßÖæ» Ùð ãUæÜæ¢ç•¤ ØãU ¼æßæ 畤Øæ ãñU 畤 Úæ…Ø ×ð´ ×æñâ×è ÚUæð», Sßæ§Ù Üê •ð¤ ©Â¿æÚ •ð¤ çÜ° Âý¼ðàæ •ð¤ ¥SÂÌæÜæð´ ×ð´ ¥æßàØ•¤ ¼ßæ¥æð´ •¤æ ÂØæü# ÂýÕ¢Ï ç•¤Øæ »Øæ ãñUÐ
I have tried the windows form RichTextBox to read the RTF file, but it always show Invalid File Format.
So what will be the best possible solution to read and modify rtf file in C#
StreamReader sr = new StreamReader(fpath, Encoding.Default, true);
string s1 = sr.ReadToEnd();
sr.Close();
also tried
using (System.Windows.Forms.RichTextBox rtBox = new System.Windows.Forms.RichTextBox())
{
// Get the contents of the RTF file. Note that when it is
// stored in the string, it is encoded as UTF-16.
string s = System.IO.File.ReadAllText(fpath);
// Convert the RTF to plain text.
rtBox.Rtf = s; // error file format invalid
string plainText = rtBox.Text;
}
The RichTextBox control can load an RTF file directly, do not use StreamReader to read RTF file because it can contain a lot of Control Characters.
After loading the file to the RichTextBox, use the Text property to get the plain text of the file.
RichTextBox also has a SaveFile method to save the modified content to a file.
I'm converting a binary file to text and dumping it into a PDF. I have this working, but I need to produce output that is identical to some samples of another program in a different language (it makes the text, then converts it to binary, so I guess I'm converting back?).
I get identical output except for one thing. I should have a bunch of dashes to set off subject headers, but instead I'm getting question marks (?). If I use Notepad++ to display the binary file, the question marks turn into some random Korean character (컴). I've tried doing result.Replace("?", "-"); and result.Replace("컴", "-"); and I've even tried checking with Contains(), but nothing is triggered.
How can I replace them?
Not sure if it will help, but here's my code:
private void btnConvertBinaryToPDF_Click(object sender, EventArgs e)
{
PdfDocument document = new PdfDocument(); //make new pdf document
PdfPage page = document.AddPage(); //add a page to the document
XGraphics gfx = XGraphics.FromPdfPage(page); //use this to draw/write on the specified page
XFont font = new XFont("Courier New", 10); //need a font to write with
string result = "";
string path = #"C:\Users\file";
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
FileStream fs = File.OpenRead(path);
int i = 1;
while (fs.Read(b, 0, b.Length) > 0)
{
string tmp = temp.GetString(b);
result += tmp;
b = new byte[1024]; //clear the buffer
}
if (result.Contains("?"))
{
Console.WriteLine("contains!");
}
result.Replace("컴", "-");
XTextFormatter tf = new XTextFormatter(gfx);
XRect rect = new XRect(40, 100, 500, 100);
tf.DrawString(result, font, XBrushes.Black, rect, XStringFormats.TopLeft);
string filename = "HelloWorld.pdf"; //make the filename
document.Save(filename); //save the document to the filename
Process.Start(filename); //open the file to show the document
}
EDIT: path contains binary data. I need to get the text representation of its contents. The above works fine, except in the case of ASCII characters numbered higher than 127.
It looks like you're simply making a mess of reading from the file. I'll assume that path contains text data; in which case, you might be better off simply using:
string result = File.ReadAllText(path);
optionally specifying an encoding:
string result = File.ReadAllText(path, Encoding.UTF8);
At the moment, you are:
treating more bytes as data than you read each iteration
not handling partial character reads
(there are also some inefficiencies in how you handle the string, the byte[] and the FileStream, but frankly that is moot if you're also getting the wrong answer)
Finally, your replace: does nothing:
result.Replace("컴", "-");
should be:
result = result.Replace("컴", "-");
(if it is still needed)
so I'm attempting to dump some RTF from the clipboard to a file.
Essentially, what's happening is that if the application see's that the user has RTF in the clipboard when they paste, it dumps that RTF to a file that is specified earlier.
The code that I was trying to use to do this is as follows:
private void saveTextLocal(bool plainText = true)
{
object clipboardGetData = Clipboard.GetData(DataFormats.Rtf);
string fileName = filename();
using (FileStream fs = File.Create(fileLoc)) { };
File.WriteAllBytes(fileLoc, ObjectToByteArray(clipboardGetData));
}
private byte[] ObjectToByteArray(Object obj)
{
if (obj == null)
{
return null;
}
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
This appears to almost work, producing the following information as the file:
ÿÿÿÿ ‰{\rtf1\ansi\deff0\deftab480
{\fonttbl
{\f000 Courier New;}
{\f001 Courier New;}
{\f002 Courier New;}
{\f003 Courier New;}
}
{\colortbl
\red128\green128\blue128;
\red255\green255\blue255;
\red000\green000\blue128;
\red255\green255\blue255;
\red000\green000\blue000;
\red255\green255\blue255;
\red000\green000\blue000;
\red255\green255\blue255;
}
\f0\fs20\cb7\cf6 \highlight5\cf4 Console\highlight3\cf2\b .\highlight5\cf4\b0 WriteLine\highlight3\cf2\b (\highlight1\cf0\b0 "pie!"\highlight3\cf2\b )}
Which does appear to be almost right. Opening the file I'm copying in Notepad++ looks like this:
{\rtf1\ansi\deff0\nouicompat{\fonttbl{\f0\fnil Courier New;}}
{\colortbl ;\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue128;\red128\green128\blue128;}
{\*\generator Riched20 6.2.9200}\viewkind4\uc1
\pard\cf1\highlight2\f0\fs20\lang2057 Console\cf3\b .\cf1\b0 WriteLine\cf3\b (\cf4\b0 "pie!"\cf3\b )\cf1\b0\par
}
Did I do something obviously wrong, and if so - how would I amend my code to fix it?
Thanks in advance!
The issue was, as madamission quite rightly pointed out, that RTF is ASCII - not binary, and thus running it through a binary converter was wholly the wrong direction.
Instead, I did a cast of the clipboard data object to get it into a string, and I wrote as you would for a normal text file. This produced the file I was expecting. The following is the working code for anyone who might find this:
private void saveTextLocal(bool plainText = true)
{
//First, cast the clipboard contents to string. Remember to specify DataFormat!
string clipboardGetData = (string)Clipboard.GetData(DataFormats.Rtf);
//This is irrelevant to the question, in my method it generates a unique filename
string fileName = filename();
//Start a StreamWriter pointed at the destination file
using (StreamWriter writer = File.CreateText(filePath + ".rtf"))
{
//Write the entirety of the clipboard to that file
writer.Write(clipboardGetData);
};
//Close the StreamReader
}
RTF is only ASCII I think and not binary so I think you should use a TextWriter instead and don't use the BinaryFormatter.
There are some related solutions here: How to create RTF from plain text (or string) in C#?
I have a rtf file in which I have to make some text replacements with some language specific characters (UTF8). After the replacements I try to save to a new rtf file but either the characters are not set right(strange characters) or the file is saved with all the rtf raw code and all the formatting.
Here is my code:
var fs = new FileStream(#"F:\projects\projects\RtfEditor\Test.rtf", FileMode.Open, FileAccess.Read);
//reads the file in a byte[]
var sb = FileWorker.ReadToEnd(fs);
var enc = Encoding.GetEncoding(1250);
//var enc = Encoding.UTF8;
var sbs = enc.GetString(sb);
var sbsNew = sbs.Replace("#test/#", "ă î â șșțț");
//first writting aproach
var fsw = new FileStream(#"F:\projects\projects\RtfEditor\diac.rtf", FileMode.Create, FileAccess.Write);
fsw.Write(enc.GetBytes(sbsNew), 0, enc.GetBytes(sbsNew).Length);
fsw.Flush();
fsw.Close();
In this aproach, the result file is the right one but the characters "șșțț" are shown as "????".
//second writing aproach
using (StreamWriter sw = new StreamWriter(fsw, Encoding.UTF8))
{
sw.Write(sbsNew);
sw.Flush();
}
In this aproach, the result file is a rtf file but with all rtf raw code and formatting and the special characters are saved right (șșțț appear correcty, no more ????)
A RTF file can directly contain 7-bit characters only. Everything else needs to be encoded into escape sequences. More detailed information can be found in e.g. this Wikipedia article.
I have a string of richtext characters/tokens that I would like to feed to a richtextbox in code.
string rt = #" {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}{\f1\fnil\fprq2\fcharset0 Biondi;}}"+
#"{\colortbl ;\red255\green0\blue0;}"+
#"{\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\f0\fs20\par"+
#"\cf1\f1 hello\cf0\f0 \ul world\par}";
I have attempted this :
System.IO.MemoryStream strm = new System.IO.MemoryStream();
byte[] b = Encoding.ASCII.GetBytes(rt);
strm.BeginRead(b, 0, b.Length, null, null);
richTextBox1.LoadFile(strm, RichTextBoxStreamType.RichText);
it didn't work.
can anyone give me a few sugestions.
BTW the rich text comes from saving from wordpad, opening the file with notepad and using the text with in to build my string
Rich textbox has a property named Rtf. Set that property to your string value. Also, your string has an extra space as the first character. I had to remove that before I saw your Hello World.
Expanding on gbogumil's answer:
string rt = #"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}{\f1\fnil\fprq2\fcharset0 Biondi;}}"+
#"{\colortbl ;\red255\green0\blue0;}"+
#"{\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\f0\fs20\par"+
#"\cf1\f1 hello\cf0\f0 \ul world\par}";
this.richTextBox1.Rtf = rt;