2010-08-11 174 views
2

因此,在我的程序中,我使用COM Auotmation(Silverlight 4中的AutomationFactory)創建一個FileSystemObject,向其中寫入一個字符串(theContent)。這種情況下的內容是一個小的UTF-8 XML文件,我使用MemoryStream將其序列化爲字符串。Scripting.FileSystemObject寫入方法失敗

字符串很好,但由於某種原因,每當我調用FileSystemObject的Write方法時,我都會收到錯誤「HRESULT 0x800A0005(來自google的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(); 
} 
+0

我只想問... *爲什麼*您使用FSO在這裏? – 2010-08-11 19:28:01

+0

本質上,我使用Silverlight(用於.NET應用程序的OOB Silverlight前端)做了一些非常有趣的事情,所以我僅限於AutomationFactory可以生成的任何內容。 – 2010-08-11 19:46:18

回答

3

我用ADODB.Stream,而不是Scripting.FileSystemObject的解決今天同樣的問題。

在Silverlight 4 OOB應用程序(即使提升信任度),您無法訪問「MyDocuments」和其他幾個與用戶相關的特殊文件夾之外的文件。您必須使用變通辦法「COM +自動化」。但是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(); 
    } 
} 
0

爲什麼不乾脆:

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

甚至

​​
+0

Silverlight應用程序沒有足夠的權限。 – 2010-08-11 19:46:56