Scripting.FileSystemObject写入方法失败

时间:2010-08-11 19:25:25

标签: c# silverlight filesystemobject comautomationfactory

所以在我的程序中我使用COM Auotmation(Silverlight 4中的AutomationFactory)来创建一个FileSystemObject,我写了一个字符串(theContent)。在这种情况下,theContent是一个小的UTF-8 XML文件,我使用MemoryStream将其序列化为字符串。

字符串很好,但出于某种原因,每当我调用FileSystemObject的Write方法时,我都会收到错误“HRESULT 0x800A0005(来自谷歌的CTL_E_ILLEGALFUNCTIONCALL)。”最奇怪的是,如果我传递另一个简单的字符串,比如“你好”,它就没有问题。

有什么想法吗?

或者,如果有一种方法可以使用FileSystemObject公开文件/文本流,我可以直接序列化,那也很好(我似乎找不到VB中没有的东西)。

提前致谢!

string theContent = System.Text.Encoding.UTF8.GetString(content, 0, content.Length);
string hello = "hello";

 using (dynamic fsoCom = AutomationFactory.CreateObject("Scripting.FileSystemObject"))
 {
      dynamic file = fsoCom.CreateTextFile("file.xml", true);
      file.Write(theContent);
      file.Write(hello);
      file.Close();
 }

2 个答案:

答案 0 :(得分:4)

我今天使用ADODB.Stream而不是Scripting.FileSystemObject解决了同样的问题。

在Silverlight 4 OOB应用程序中(即使提升信任度),您也无法访问“MyDocuments”之外的位置以及其他一些与用户相关的特殊文件夹。您必须使用解决方法'COM + Automation'。但是Scripting.FileSystemObject对文本文件非常有用,它无法处理二进制文件。幸运的是,你也可以在那里使用ADODB.Stream。并且处理二进制文件就好了。这是我的代码,使用Word模板,.dotx文件测试:

public static void WriteBinaryFile(string fileName, byte[] binary)
{
    const int adTypeBinary = 1;
    const int adSaveCreateOverWrite = 2;
    using (dynamic adoCom = AutomationFactory.CreateObject("ADODB.Stream"))
    {
        adoCom.Type = adTypeBinary;
        adoCom.Open();
        adoCom.Write(binary);
        adoCom.SaveToFile(fileName, adSaveCreateOverWrite);
    }
}

文件读取可以这样完成:

public static byte[] ReadBinaryFile(string fileName)
{
    const int adTypeBinary = 1;
    using (dynamic adoCom = AutomationFactory.CreateObject("ADODB.Stream"))
    {
        adoCom.Type = adTypeBinary;
        adoCom.Open();
        adoCom.LoadFromFile(fileName);
        return adoCom.Read();
    }
}

答案 1 :(得分:0)

为什么不呢:

File.WriteAllText("file.xml", theContent, Encoding.UTF8);

甚至

File.WriteAllBytes("file.xml", content);