Thread: File Reading Help

  1. #1
    Apprentice Swordsman's Avatar
    Join Date
    Apr 2007
    Posts
    38

    File Reading Help

    Hi all,

    My C# is VERY basic, but I've been given the task of converting a C++ program into C# anyway. This part of the program is pretty simple, and is trying to read a certain amount of bytes out of a file into a struct. C++ example:

    Code:
    struct myS
    {
         char c[4];
         DWORD a;
         DWORD b;
    }
    
    .....
    
    myS m_myS;
    
    fread(&m_myS, sizeof(m_myS), 1, myFileStream);
    Obviously, now I could get myS.a and the like of.

    Either way, I need to recreate this in C# and I can't seem to work out how. Using Read() throws an error as it wants a byte array. I can't get the sizeof(myS) nor m_MyS.

    Am I missing something here?

  2. #2
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Quote Originally Posted by Swordsman View Post
    Either way, I need to recreate this in C# and I can't seem to work out how. Using Read() throws an error as it wants a byte array. I can't get the sizeof(myS) nor m_MyS.

    Am I missing something here?
    Yeah. Learning C#...

    You are trying to fly a plane before knowing about all the knobs.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  3. #3
    Apprentice Swordsman's Avatar
    Join Date
    Apr 2007
    Posts
    38
    You suggest that I should learn C# by some other way apart from programming in C#? Should I give Go a bash to see if it helps instead?

  4. #4
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Quote Originally Posted by Swordsman View Post
    You suggest that I should learn C# by some other way apart from programming in C#? Should I give Go a bash to see if it helps instead?
    Don't get all so worked up already. I didn't even warm up.

    What I'm suggesting is that you indeed learn C#. If your first attempt at porting that C code to C# is to call a function with the exact same name, you obviously need to learn C#.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  5. #5
    Apprentice Swordsman's Avatar
    Join Date
    Apr 2007
    Posts
    38
    Quote Originally Posted by Fordy View Post
    What you are writing inst C#...its C. Might sound similar...but they aren't
    I'm pretty sure that I answered this within the absolute first paragraph (and the program is actually C++ that uses this method because it's quicker):

    but I've been given the task of converting a C++ program into C# anyway. C++ example:
    Quote Originally Posted by Mario F
    What I'm suggesting is that you indeed learn C#. If your first attempt at porting that C code to C# is to call a function with the exact same name, you obviously need to learn C#.
    No, my first port of call was looking up general File IO tutorials in Google, using Intellisense to go through the list, then I somehow ended up reading about unsafe code which I was thinking of using, before reading the conclusion that stated that there's almost no reason to use it in C#. Hence, I gathered that I'm probably missing a method somewhere which will do this, and thought a post on a C# related forum would grab me the answer in the shortest time but has lead to one guy who didn't read the question and another guy who is talking in Taoist/massive presumptuous statements. Forget it, I'll ask around the office.
    Last edited by Swordsman; 06-22-2011 at 08:34 AM.

  6. #6
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Quote Originally Posted by Swordsman View Post
    I've been given the task of converting a C++ program into C#
    And that's totally fine. But how do you plan to complete this task if you don't know one thing about C#?
    Or better yet, why did you even accept it?

    You surely aren't confusing us with your school teacher...

    Anyways, that's the last you hear of me on this thread. Read the forum rules.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  7. #7
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Quote Originally Posted by Swordsman View Post
    I'm pretty sure that I answered this within the absolute first paragraph (and the program is actually C++ that uses this method because it's quicker):
    Your right. That's why I deleted the post. I didn't read your post well enough

  8. #8
    Registered User
    Join Date
    Mar 2009
    Location
    england
    Posts
    209
    System.IO.FileStream gets your stream. Then you could use System.IO.BinaryReader to read off the data into the variables in your object. Your myS object in C# could look something like this...

    Code:
        class myS
        {
            public String c { get; set; }
            public uint a { get; set; }
            public uint b { get; set; }
    
            public myS(FileStream stream)
            {
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    this.c = Encoding.Default.GetString(reader.ReadBytes(4));
                    this.a = reader.ReadUInt32();
                    this.b = reader.ReadUInt32();
                }
            }
        }

  9. #9
    Registered User
    Join Date
    Jan 2010
    Posts
    412
    Code:
    using System.Runtime.InteropServices;
    
    [StructLayout(LayoutKind.Sequential)]
    public struct myS
    {
    	[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    	public char[] c;
    	public UInt32 a;
    	public UInt32 b;
    }
    
    static class NativeInterop
    {
    	public static S MarshalStruct<S>(System.IO.Stream input) where S : struct
    	{
    		int size = Marshal.SizeOf(typeof(S)); // size of the managed structure
    		byte[] buffer = new byte[size]; // byte buffer
    		input.Read(buffer, 0, size); // read unmanaged struct
    		GCHandle gch = GCHandle.Alloc(buffer, GCHandleType.Pinned); // allocate a pinned handle to the buffer to prevent the GC from moving it
    		S ret = (S)Marshal.PtrToStructure(gch.AddrOfPinnedObject(), typeof(S)); // marshal the buffer
    		gch.Free(); // release the handle
    		return ret;
    	}
    }
    
    myS s = NativeInterop.MarshalStruct<myS>(new System.IO.FileStream(@"c:\some.file", FileMode.Open, FileAccess.Read));
    Add your own error handling as several of those methods can throw exceptions.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 13
    Last Post: 05-31-2009, 11:30 AM
  2. File I/O (Reading from a Random-Access File)
    By VersEtreOuNe in forum C++ Programming
    Replies: 25
    Last Post: 02-14-2008, 05:13 AM
  3. Reading flat file and generating tagged file
    By AngKar in forum C# Programming
    Replies: 4
    Last Post: 03-24-2006, 08:29 AM
  4. reading from file and writing in a nother file
    By undisputed007 in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2004, 02:17 PM