2011-07-04 40 views
1

我正在用Windows Phone 7中的C#覆盖文件。当我这样做时,每行的开头都会添加一个看似随机的字符。编写一个文件,添加随机字符到每行的开头

这是怎么发生的?

代码:

public static bool overwriteFile(string filename, string[] inputArray) 
    { 
     try 
     { 
      IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication(); 

      FileStream stream = store.OpenFile(filename, FileMode.Create); 
      BinaryWriter writer = new BinaryWriter(stream); 

      foreach (string input in inputArray) 
      { 
       writer.Write(input + "\n"); 
      } 

      writer.Close(); 
      return true; 

     } 
     catch (IOException ex) 
     { 
      return false; 
     } 
    } 

Lodaing代码:

public static Idea[] getFile(string filename) 
    { 
     try 
     { 
      IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication(); 
      string fileContents = null; 
      if (store.FileExists(filename)) // Check if file exists 
      { 
       IsolatedStorageFileStream save = new IsolatedStorageFileStream(filename, FileMode.Open, store); 

       StreamReader streamReader = new StreamReader(save); 
       fileContents = streamReader.ReadToEnd(); 
       save.Close(); 

      } 

      string[] lines = null; 
      if (fileContents != null) 
      { 
       lines = fileContents.Split('\n'); 
      } 



      Idea[] ideaList = null; 
      if (lines != null) 
      { 
       ideaList = new Idea[lines.Length]; 
       for (int i = 0; i < lines.Length; i++) 
       { 
        ideaList[i] = new Idea(lines[i].TrimEnd('\r')); 
       } 
      } 

      return ideaList; 
     } 
     catch (IOException ex) 
     { 
      return null; 
     } 
    } 
+0

你是如何加载文件? – BrokenGlass

+0

已在上面添加 – Chris

+0

您是否检查过“输入”实际上是否包含您认为它包含的内容? – ChrisF

回答

6

随机字符是一个长度前缀;见http://msdn.microsoft.com/en-us/library/yzxa6408.aspx

您应该使用某种类型的TextWriter将字符串写入文件;不是BinaryWriter。

StreamWriter可能是最好的,然后你可以使用WriteLine方法。

+0

谢谢你工作完美! – Chris

+0

不用担心队友。 –

1

而不是使用'\n'的,请尝试使用Environment.NewLine

+0

好的提示,但没有解决我的问题 – Chris

0

尝试改变这种

writer.Write(input + "\n");

writer.WriteLine(input);

+0

WriteLine方法似乎不存在? – Chris

1

您正在使用BinaryWriter进行书写,并使用TextReader进行读取。将您的写代码更改为使用StreamWriter(它是一个TextWriter)而不是BinaryWriter。这也会让你了解Naveed推荐的WriteLine方法。

+0

感谢您的帮助! – Chris

相关问题