Billy ONeal
Billy ONeal

Reputation: 106530

Who owns MemoryStream objects placed on the clipboard? (Or should something other than MemoryStream be used?)

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)

Upvotes: 8

Views: 1144

Answers (1)

giammin
giammin

Reputation: 18958

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

Upvotes: 1

Related Questions