开发者

Writing a file adding random characters to start of each line

I'm overwriting a file using C# in Windows Phone 7. When I do this a seemingly random character is added to the start of each line.

Why is this happening?

Code:

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 Code:

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)
        开发者_StackOverflow中文版    {
                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;
        }
    }


The random character is a length prefix; see http://msdn.microsoft.com/en-us/library/yzxa6408.aspx.

You should be using some type of TextWriter to write strings to the file; NOT a BinaryWriter.

A StreamWriter might be the best and then you could use the WriteLine method.


Instead of using '\n', try using Environment.NewLine


You are using a BinaryWriter to write, and a TextReader to read. Change your write code to use a StreamWriter (which is a TextWriter) instead of a BinaryWriter. This will also get you the WriteLine method that Naveed recommends.


try changing this

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

to

writer.WriteLine(input);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜