I have a method like this:
public DataObject GetClipboardData()
{
var result = new DataObject();
result.SetText(this.fallbackText.ToString());
result.SetData(DataFormats.Html, this.GenerateHtml(), false);
return result;
}
where GenerateHtml
returns a MemoryStream
.
Do I need to be worried about closing the MemoryStream
object? Or should I use some other type of object to place raw bytes on the clipboard?
(I tried byte[]
but this places the text "System.Byte[]"
or similar on the clipboard)
You can re-use the MemoryStream by Setting the Position to 0 and the Length to 0. By setting the length to 0 you do not clear the existing buffer, it only resets the internal counters.
MemoryStream does not have any unmanaged resources to dispose, so you don't technically have to dispose of it. The effect of not disposing a MemoryStream is roughly the same thing as dropping a reference to a byte[] -- the GC will clean both up the same way.
MemoryStream(Byte[]) Initializes a new non-resizable instance of the MemoryStream class based on the specified byte array. MemoryStream(Byte[], Boolean) Initializes a new non-resizable instance of the MemoryStream class based on the specified byte array with the CanWrite property set as specified.
You would use the FileStream to read/write a file but a MemoryStream to read/write in-memory data, such as a byte array decoded from a string. You would not use a Stream in and of itself, but rather use it for polymorphism, i.e. passing it to methods that can accept any implementation of Stream as an argument.
I think that if an object implements IDisposable
is a good thing to dispose it when you don't need it anymore.
DataObject
provides a basic implementation of the IDataObject
interface so why don't you derive from it:
public sealed class HtmlDataObject : DataObject, IDisposable
{
protected MemoryStream HtmlMemoryStream { get; set; }
public HtmlDataObject(MemoryStream memoryStream, string fallBackText)
{
HtmlMemoryStream = memoryStream;
SetText(fallBackText);
SetData(DataFormats.Html, false, HtmlMemoryStream );
}
public void Dispose()
{
HtmlMemoryStream .Dispose();
}
}
So your method can be changed:
public HtmlDataObject GetClipboardData()
{
return new HtmlDataObject(this.GenerateHtml(), this.fallbackText.ToString());
}
And you can put it into an using statement
or Dispose()
it when you have finished using it.
Final thought: You should not worry about clipboard data because the DataObject
will be destroyed anyway when you exit the application and your clipboard will lose what you put inside with it.
http://msdn.microsoft.com/en-us/library/office/gg278673.aspx
If you want that the stream is persisted after disposing it and/or when the application exit you have to use Clipboard.SetDataObject with the copy
parameter = true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With