Bug 27086

Summary: Writing in asynchronous FileStream adds 0 bytes at the beginning of the file
Product: [Mono] Class Libraries Reporter: guillaume.turri
Component: mscorlibAssignee: Marek Safar <masafa>
Status: RESOLVED FIXED    
Severity: normal CC: masafa, mono-bugs+mono
Priority: ---    
Version: master   
Target Milestone: Untriaged   
Hardware: PC   
OS: Linux   
Tags: Is this bug a regression?: ---
Last known good build:
Attachments: Test case

Description guillaume.turri 2015-02-16 03:35:31 UTC
Created attachment 9843 [details]
Test case

Hi,

I just tested this on a version of Mono build from source, from the current HEAD (bc57fda921d7c35dd7f52f71bdbdff9e831f328e) on Ubuntu.

* How to reproduce: Run the code attached with this bug report (and copy/pasted below)
* Expected behavior: We can read the DateTime we just wrote (ie: 03/04/1985)
* Behavior with .Net: same as the expected one
* Actual behavior: The DateTime read is "01/01/0001 12:00 AM"

Some more details:
* When we remove the FileOptions.Asynchronous flag, it works fine
* If we don't write the Guid (ie: if we only write the TimeStamp), it works fine
* When we open the file with an hexadecimal editor, it seems the file starts with several 0 bytes, and then we have the expected content (and "01/01/0001 12:00 AM" is the result of DateTime.FromBinary(0), so the issue if likely when we write, not when we read).

Regards,
Guillaume


---

    using System;
    using System.IO;
    using System.Linq;
    
    public class Program
    {
    	public static void Main(String[] args)
    	{
    		string filename = "myfilename";
    		File.Delete (filename);
    
    		using (var file = new FileStream (filename, FileMode.Append, FileAccess.Write, FileShare.Read, 4096, FileOptions.Asynchronous))
    		using (var writer = new BinaryWriter (file)){
    			WriteTimeStamp (writer);
    			WriteGuid (writer);
     
    			writer.Flush ();
     
    			file.Close ();
    			writer.Close ();
    		}
    		ReadFile (filename);
    	}
    
    	private static void WriteTimeStamp(BinaryWriter writer){
    		var timeStamp = new DateTime (1985, 04, 03);
    		writer.Write (timeStamp.ToBinary ());
    	}
    
    	private static void WriteGuid(BinaryWriter writer){
    		var id = new Guid (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    		writer.Write (id.ToByteArray ());
    	}
    
    	private static void ReadFile(string filename){
    		using (var inputStream = new FileStream (filename, FileMode.Open))
    		using (var reader = new BinaryReader (inputStream)) {
    			var timeStamp = DateTime.FromBinary (reader.ReadInt64 ());
    			Console.WriteLine (timeStamp);
    		}
    	}
    }
Comment 1 Marek Safar 2015-02-18 06:57:02 UTC
Fixed in master
Comment 2 guillaume.turri 2015-02-18 07:34:56 UTC
Perfect!
Thanks!