Category Archives: IO

Reading binary data in C#

This caption is taken directly from an article i found here. The final result of this post is the following code:

/// <summary>
/// Reads data from a stream until the end is reached. The
/// data is returned as a byte array. An IOException is
/// thrown if any of the underlying IO calls fail.
/// </summary>
/// <param name="stream">The stream to read data from</param>
/// <param name="initialLength">The initial buffer length</param>
public static byte[] ReadFully (Stream stream, int initialLength)
{
    // If we've been passed an unhelpful initial length, just
    // use 32K.
    if (initialLength < 1)
    {
        initialLength = 32768;
    }
    
    byte[] buffer = new byte[initialLength];
    int read=0;
    
    int chunk;
    while ( (chunk = stream.Read(buffer, read, buffer.Length-read)) > 0)
    {
        read += chunk;
        
        // If we've reached the end of our buffer, check to see if there's
        // any more information
        if (read == buffer.Length)
        {
            int nextByte = stream.ReadByte();
            
            // End of stream? If so, we're done
            if (nextByte==-1)
            {
                return buffer;
            }
            
            // Nope. Resize the buffer, put in the byte we've just
            // read, and continue
            byte[] newBuffer = new byte[buffer.Length*2];
            Array.Copy(buffer, newBuffer, buffer.Length);
            newBuffer[read]=(byte)nextByte;
            buffer = newBuffer;
            read++;
        }
    }
    // Buffer is now too big. Shrink it.
    byte[] ret = new byte[read];
    Array.Copy(buffer, ret, read);
    return ret;
}

Reverse mapping of drive letter to server address

You need the pure server address of a remote directory mapped to a drive letter? Try this:

[DllImport("Mpr.dll", CharSet = CharSet.Auto)]
private static extern int WNetGetConnection(
    [MarshalAs(UnmanagedType.LPTStr)] string localName,
    [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
    ref int length);

public static String GetServerPath(char driverLetter)
{
    try
    {
        int length = 1024;
        StringBuilder result = new StringBuilder(length);
        WNetGetConnection(driverLetter + ":", result, ref length);

        return result.ToString();
    }
    catch
    {
    }
    return null;
}

public static String GetServerPath(String filename)
{
    if (filename.Length > 1 && filename[1] == ':')
    {
        String serverpath = GetServerPath(filename[0]);
        if (serverpath != null && serverpath.Trim().Length > 0)
            filename = serverpath + filename.Substring(2);
    }
    return filename;
}