C#将HTML格式的表复制到剪贴板

时间:2015-05-18 13:06:39

标签: c# html copy clipboard text-formatting

我需要从本地网络地址获取HTML格式的表格,填写其中的几个字段然后将其复制到剪贴板。 我最接近解决方案的是下面的代码:

string text = File.ReadAllText(@"[network path]");
        text = text.Replace("::TTYPE::", "BLABLABLA");
        text = text.Replace("::VERSIONNAME::", SWVBox.Text);
        text = text.Replace("::TRESULT::", FinalResult());
        text = text.Replace("::SERVERPATH::", "BLABLABLA");
        text = text.Replace("::TESTERNAME::", Environment.UserName);
        text = text.Replace("::COMMENTS::", "BLABLABLA");

        Clipboard.SetText(text);

此代码已将HTML文件中包含的数据复制为纯文本,因此我也尝试了Clipboard.SetText(text, TextDataFormat.Html);但它无效。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这可能是您正在寻找的内容:https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj159584.aspx

以下是该页面的代码示例(看起来您不需要处理图像的部分):

{
    // Prepare some HTML for copying to the Clipboard.
    const string imgSrc = "ms-appx-web:///assets/windows-sdk.png";
    const string htmlFragment = "This sample shows how to copy HTML to the "
            + "Clipboard. <br />"
            + "To <b>copy</b>, add text formats to a <i>DataPackage</i>, "
            + "and then pass <i>DataPackage</i> the to Clipboard.<br /> "
            + "To handle local image files (such as the one below), use "
            + "resourceMap collection."
            + "<br /><img id=\"scenario1LocalImage\" src=\""
            + imgSrc
            + "\" /><br />";

    string htmlFormat = HtmlFormatHelper.CreateHtmlFormat(htmlFragment);

    // Create a DataPackage object.
    var dataPackage = new DataPackage();

    // Set the content of the DataPackage as HTML format.
    dataPackage.SetHtmlFormat(htmlFormat);

    // Populate the resource map with RandomAccessStreamReference objects 
    // corresponding to local image files embedded in the HTML.
    var imgUri = new Uri(imgSrc);
    var imgRef = RandomAccessStreamReference.CreateFromUri(imgUri);
    dataPackage.ResourceMap[imgSrc] = imgRef;

    try
    {
        // Set the DataPackage to the clipboard.
        Clipboard.SetContent(dataPackage);
        OutputText.Text = "HTML format was copied to the Clipboard. ";
    }
    catch (Exception ex)
    {
        // Copying data to the Clipboard can fail if, another application is 
        // holding the Clipboard open.
        rootPage.NotifyUser("Error copying content to Clipboard: " +
            ex.Message + ". Try again", NotifyType.ErrorMessage);
    }
}