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

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


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