Who owns the MemoryStream objects located on the clipboard? (Or do you need to use something other than a MemoryStream?)

I have a way 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 have to worry about closing a MemoryStream object? Or should I use some other type of object to place the raw bytes on the clipboard?

(I tried byte[] , but this puts the text "System.Byte[]" or similar on the clipboard)

+7
c # clipboard wpf memorystream
source share
1 answer

I think that if an object implements IDisposable , it is a good thing to get rid of it when you no longer need it.

DataObject provides the basic implementation of the IDataObject interface, so why not get it out of 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(); } } 

Thus, your method can be changed:

 public HtmlDataObject GetClipboardData() { return new HtmlDataObject(this.GenerateHtml(), this.fallbackText.ToString()); } 

And you can put it in using statement or Dispose() when you finish using it.

Final thought:. You do not have to worry about the clipboard data, because the DataObject will be destroyed when you exit the application and your clipboard will lose what you put inside it. http://msdn.microsoft.com/en-us/library/office/gg278673.aspx

If you want the stream to remain after deleting it and / or when exiting the application, you should use Clipboard.SetDataObject with copy parameter = true

+1
source share

All Articles