Search code examples
c#.netvariablesmemorystreamconverters

Saving File conversion to variable instead of physical location


I'm trying out to use the XML - Mind converter https://www.xmlmind.com/foconverter/ to convert some xsl-fo to an rtf and this works well . Just to be clear this is nothing specific to the conveter or its functionality but just a clarification I would like to get which is why I am asking this on stack overflow .

So I have the following code (that was obtained from some documentation)

string foFilePath = @"D:\Temp\test.fo";
string ourPutFilePath = @"D:\Temp\test.rtf";


                Converter converter = new Converter();
                converter.OutputFormat = OutputFormat.Rtf;
                converter.OutputEncoding = "windows-1252";
                converter.ImageResolution = 120;


                converter.SetInput(foFilePath);
                converter.SetOutput(ourPutFilePath);
                
                converter.Convert();

What happens here is quite simple Reads a file from the input path and stores the converted file in the specified output . The question I would like to clarify here is , wheather it would be possible to store this content that is being saved in the file out put path within a variable as well to may be do some processing during the application runtime ?

Maybe I can use the MemoryStream for it ? I'm just not sure how to do it and would really appreciate some help here.

I understand that I can always read it back from the file output path but I am looking for something better than that as saving the file to a certain location may not always be possible in my case

EDIT :- The converter.SetOutput() method allows 3 overloads in the parameters

  1. String fileName
  2. Stream stream
  3. TextWriter writer

Solution

  • Sine you need the output as a string you could try doing something like this

          string content;
          using (var stream = new MemoryStream())
          {
            using (var writer = new StreamWriter(stream))
            {
              Converter converter = new Converter();
              converter.OutputFormat = OutputFormat.Rtf;
              converter.OutputEncoding = "windows-1252";
              converter.ImageResolution = 120;
              converter.SetInput(foFilePath);
              converter.SetOutput(writer);
              converter.Convert();
              stream.Position = 0;
              content = Encoding.UTF8.GetString(stream.ToArray());
            }
          } 
    

    I'm not sure about the Encoding though, and if the Convert() uses a different encoding this might not work