所以我试图将一些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 )}
这看起来几乎是正确的。打开我在Notepad ++中复制的文件如下所示:
{\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
}
我做了一些明显错误的事情,如果是的话 - 我将如何修改我的代码来修复它?
提前致谢!
答案 0 :(得分:3)
正如madamission非常正确地指出的那样,问题是RTF是ASCII - 而不是二进制,因此通过二进制转换器运行它完全是错误的方向。
相反,我做了一个剪贴板数据对象的演员,把它变成了一个字符串,我写的就像普通的文本文件一样。这产生了我期待的文件。以下是可能找到此内容的任何人的工作代码:
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
}
答案 1 :(得分:2)
RTF只是我想的ASCII而不是二进制,所以我认为你应该使用TextWriter而不要使用BinaryFormatter。
这里有一些相关的解决方案:How to create RTF from plain text (or string) in C#?