Below is a c# code whose purpose is to append an image to a .rtf file that already has text image. When i run the code, i get the error that says “Error: File format is not valid”.
Program.cs code
static void Main(string[] args)
{
FileStreamWriter fileStreamWriter = new FileStreamWriter();
fileStreamWriter.StreamWriterThing();
FileStreamWriter.AddImageToRTF("Text3.rtf","demo.bmp");
Console.ReadLine();
}
}
FileStreamWriter.cs file code
public void StreamWriterThing()
{
FileStream fs2 = new FileStream("Text3.rtf", FileMode.OpenOrCreate,
FileAccess.Write);
StreamWriter sr1 = new StreamWriter(fs2);
sr1.WriteLine("n" + "Writing data into file using stream writer");
sr1.Close();
fs2.Close();
string Fdata;
FileStream fs3 = new FileStream("Text3.rtf", FileMode.OpenOrCreate,
FileAccess.Read);
using (StreamReader sr2 = new StreamReader(fs3))
{
Fdata = sr2.ReadToEnd();
sr2.Close();
}
Console.WriteLine(Fdata);
fs3.Close();
}
public static void AddImageToRTF(string rtfFilePath, string imagePath)
{
try
{
// Load existing RTF content
RichTextBox richTextBox = new RichTextBox();
richTextBox.LoadFile(rtfFilePath);
// Load the image from the file
Image image = Image.FromFile(imagePath);
// Create a valid RTF template with the image placeholder
string rtfTemplate = $@"{{rtf1ansideff0{{*imageresolution 96}}
{{*pngblip{{*name Image1 *filename ""{imagePath}"" *flags 0 *tx 0 *ty 0
*w 0 *h 0}}}}}}";
// Set the RTF content to the template
richTextBox.SelectedRtf = rtfTemplate;
// Save the modified RTF back to the file
richTextBox.SaveFile(rtfFilePath, RichTextBoxStreamType.RichText);
Console.WriteLine("Image successfully added to RTF.");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
Where could i be going wrong?