1

The idea of my program is to allow the user to save his data in a cloud. The data is stored in binary serialized files.

Serialization Code looks like so:

FileStream Stream = new FileStream(..., FileMode.Create); // create stream
BinaryFormatter Formatter = new BinaryFormatter(); // create formatter
Formatter.Serialize(Stream, ObjectToSerialize); // serialize
Stream.Close();

The Problem is that when I upload the serialized file, with the following code:

FtpWebRequest Request = (FtpWebRequest)WebRequest.Create(new Uri(...));
Request.Method = WebRequestMethods.Ftp.UploadFile;

Request.Credentials = new NetworkCredential(..., ...);
string Path = System.IO.Path.GetDirectoryName(...;
StreamReader SourceStream = new StreamReader(Path);
Request.UseBinary = true;
byte[] FileContents = Encoding.Default.GetBytes(SourceStream.ReadToEnd());
SourceStream.Close();
Request.ContentLength = FileContents.Length;

Stream RequestStream = Request.GetRequestStream();
RequestStream.Write(FileContents, 0, FileContents.Length);
RequestStream.Close();

FtpWebResponse Response = (FtpWebResponse)Request.GetResponse();

Response.Close(); 

the file encoding changes (I am not sure about that.. if the encoding is the problem but I think so) and I am not able to deserialize the file anymore, exceptions occure. Do you have a idea how to do not damage the file?

Best Regards!

3
  • We need more details. Show us the Exception. Commented May 9, 2014 at 21:42
  • This is orthogonal to your question, but you really don't want to use BinaryFormatter for this. Once you upgrade the client you're going to have lots of problems. You should look into other types of serialization formats, like XML or Json. BinaryFormatter is meant as a transport format, between different modules of your system, not as a storage format which will/should survive an upgrade of one part of the system. Commented May 9, 2014 at 21:55
  • To continue on what Lasse said, ...Or use a binary formatting that is not tied to assembly versions, like proto-buf.net Commented May 9, 2014 at 21:56

1 Answer 1

1

Encoding only applies to text, and you're dealing with a binary file here. You should not attempt to read it as a string. The "encoding changed" because you are using Encoding.Default which depends on the current configuration of your operating system.

Just change the code to:

string Path = System.IO.Path.GetDirectoryName(...);
// StreamReader SourceStream = new StreamReader(Path);
// Request.UseBinary = true;
byte[] FileContents = File.ReadAllBytes(Path);
// SourceStream.Close();

if you want to read an entire binary file in memory.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.