如何将剪贴板中的RTF文件保存为C#?

如何将剪贴板中的RTF文件保存为C#?,c#,clipboard,rtf,C#,Clipboard,Rtf,因此,我试图将一些RTF从剪贴板转储到一个文件中 实际上,如果应用程序在粘贴时看到用户在剪贴板中有RTF,它会将该RTF转储到前面指定的文件中 我尝试使用的代码如下所示: private void saveTextLocal(bool plainText = true) { object clipboardGetData = Clipboard.GetData(DataFormats.Rtf); string fileName = filename(); using (F

因此,我试图将一些RTF从剪贴板转储到一个文件中

实际上,如果应用程序在粘贴时看到用户在剪贴板中有RTF,它会将该RTF转储到前面指定的文件中

我尝试使用的代码如下所示:

private void saveTextLocal(bool plainText = true)
{
    object clipboardGetData = Clipboard.GetData(DataFormats.Rtf);
    string fileName = filename();
    using (FileStream fs = File.Create(fileLoc)) { };
    File.WriteAllBytes(fileLoc, ObjectToByteArray(clipboardGetData));
}
private byte[] ObjectToByteArray(Object obj)
{
    if (obj == null)
    {
        return null;
    }
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);
    return ms.ToArray();
}
这似乎几乎起作用,生成以下信息作为文件:

    ÿÿÿÿ          ‰{\rtf1\ansi\deff0\deftab480

{\fonttbl
{\f000 Courier New;}
{\f001 Courier New;}
{\f002 Courier New;}
{\f003 Courier New;}
}

{\colortbl
\red128\green128\blue128;
\red255\green255\blue255;
\red000\green000\blue128;
\red255\green255\blue255;
\red000\green000\blue000;
\red255\green255\blue255;
\red000\green000\blue000;
\red255\green255\blue255;
}

\f0\fs20\cb7\cf6 \highlight5\cf4 Console\highlight3\cf2\b .\highlight5\cf4\b0 WriteLine\highlight3\cf2\b (\highlight1\cf0\b0 "pie!"\highlight3\cf2\b )}
这似乎几乎是正确的。在记事本++中打开我要复制的文件如下所示:

{\rtf1\ansi\deff0\nouicompat{\fonttbl{\f0\fnil Courier New;}}
{\colortbl ;\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue128;\red128\green128\blue128;}
{\*\generator Riched20 6.2.9200}\viewkind4\uc1 
\pard\cf1\highlight2\f0\fs20\lang2057 Console\cf3\b .\cf1\b0 WriteLine\cf3\b (\cf4\b0 "pie!"\cf3\b )\cf1\b0\par
}
我是否做了一些明显错误的事情,如果是,我将如何修改我的代码来修复它


提前谢谢

我认为RTF只是ASCII码,而不是二进制码,因此我认为您应该使用TextWriter,而不要使用BinaryFormatter


这里有一些相关的解决方案:

正如madamission非常正确地指出的那样,问题是RTF是ASCII-而不是二进制,因此通过二进制转换器运行RTF完全是错误的方向

取而代之的是,我对剪贴板数据对象进行了转换,将其转换为字符串,并像您对普通文本文件那样编写。这产生了我期待的文件。以下是适用于可能发现此问题的任何人的工作代码:

private void saveTextLocal(bool plainText = true)
{
    //First, cast the clipboard contents to string. Remember to specify DataFormat!
    string clipboardGetData = (string)Clipboard.GetData(DataFormats.Rtf);

    //This is irrelevant to the question, in my method it generates a unique filename
    string fileName = filename();

    //Start a StreamWriter pointed at the destination file
    using (StreamWriter writer = File.CreateText(filePath + ".rtf"))
    {
        //Write the entirety of the clipboard to that file
        writer.Write(clipboardGetData);
    };
    //Close the StreamReader
}

你完全正确!我已经包括了固定代码作为答案。谢谢你的帮助!美好的很高兴我能帮忙!