Non-static error when trying to load filestream to RichTextBox from Gzip decompress procedure
-
26-02-2021 - |
Frage
Basically all I want is to load a Gziped file into a rich text box. I found some code on the MS .NET site for decompressing the file. Now I want to point that stream to a rich text box, but I keep getting the error "An object reference is required for the non-static field, method, or property 'WindowsFormsApplication1.Form1.richTextBox1' "
Code is here. What am I doing wrong? Thanks in advance.
public static void Decompress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Get original file extension, for example
// "doc" from report.doc.gz.
string curFile = fi.FullName;
string origName = curFile.Remove(curFile.Length -
fi.Extension.Length);
//Create the decompressed file.
using (FileStream outFile = File.Create(origName))
{
using (GZipStream Decompress = new GZipStream(inFile,
CompressionMode.Decompress))
{
// Copy the decompression stream
// into the output file.
Decompress.CopyTo(outFile);
richTextBox1.LoadFile(Decompress.CopyTo(outFile), RichTextBoxStreamType.PlainText);
// problem right here ^^^^
}//using
}//using
}//using
}//DeCompress
Lösung
Just a hunch, but try this instead:
richTextBox1.LoadFile(outFile, RichTextBoxStreamType.PlainText);
The Decompress.CopyTo(outFile)
is a method and doesn't return anything, which is probably why the LoadFile method is coughing on that line.
Also, change your function to this (you can't have your control referenced in a static method):
public void Decompress(FileInfo fi)
Andere Tipps
What I ended up doing is a hack, but basically I dump the uncompressed data to a file then load that file in the RTF. I'm sure it's much slower than streaming it directly to RTF but I could not get that piece working. It's functional, but not great. I pass in the fi variable to Decompress based on what the program arguement is, and I then assign that program to be run when a user double clicks on a gz file in windows. So the code looks like this:
public void Decompress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Get original file extension, for example
// "doc" from report.doc.gz.
string curFile = fi.FullName;
string origName = curFile.Remove(curFile.Length -
fi.Extension.Length);
//Create the decompressed file.
using (FileStream outFile = File.Create(origName))
{
using (GZipStream Decompress = new GZipStream(inFile,
CompressionMode.Decompress))
{
// Copy the decompression stream
// into the output file.
Decompress.CopyTo(outFile);
Decompress.Close();
outFile.Close();
inFile.Close();
rtbOut.LoadFile(origName, RichTextBoxStreamType.PlainText);
string tmp = rtbOut.Text;
}//using
}//using
}//using
} //Decompress