简体   繁体   中英

Converting TFileStream to C#

I've been trying to convert the following Delphi code to C#. I've never worked with Delphi before. I keep running into several errors regarding the FileStream .

Cannot convert from RAMPhdrrec to byte[]

Best overloaded match for Read(byte[], int, int) has some invalid arguments

Also, I'm not able to reference any of the fields in the structure in C#.

Here's the Delphi definition for TFileStream :

function Read(var Buffer; Count: Longint): Longint; virtual; abstract;

and C# :

FileStream.Read Method (Byte[], Int32, Int32)

How is the Delphi code working with only two parameters?

Delphi code:

CONST
   HeaderSize=128;
Type

RAMPhdrrec = packed record
  //Other fields
  FirstRAMPtime: TDateTime;
  LastRAMPTime: TDateTime;
end;

var
  Header:RAMPhdrrec;

Function TestingForm.Testing(PathName:String):Boolean;
StartTime:TDateTime;
   EndTime:TDateTime;
begin
    if RampOpen then
    begin
       RampStream.Free;
    end;
    Try
      RampStream:=TFileStream.Create(PathName,fmOpenReadWrite OR fmShareExclusive );
    except
      ShowMessage(//error message here);
      Testing:=false;
      RampOpen:=False;

    end;
    try
        RampStream.Read(Header,HeaderSize);
        StartTime:=Header.FirstRAMPtime;
        EndTime:=Header.LastRAMPTime;

Here's the C#:

const int HeaderSize = 128;

public struct RAMPhdrrec
        {
            double FirstRAMPtime;
            double LastRAMPTime;
        }

RAMPhdrrec Header;

public Boolean Testing(string PathName)
        {
            double StartTime, EndTime;

            try
            {
                RampStream = new FileStream(PathName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            catch
            {
                System.Windows.MessageBox.Show("//error message here");
                RampOpen = false;
                return false;              
            }

            try
            {
                RampStream.Read(Header, HeaderSize); //error
            }
            catch
            {
                return false;
            }
            return true;
        }

I believe this C# code equivalent to Delphi code above.

BinaryReader br = new BinaryReader(new FileStream(PathName, 
                               FileMode.Open,  
                               FileAccess.ReadWrite, 
                               FileShare.None));

StartTime = br.readDouble();
EndTime   = br.readDouble();

In Delphi, System.TDateTime is alias to Double type with integral part is number of days since 12/30/1899 and fractional part is fraction of a 24 hour day that has elapsed. See TDateTime documentation . So if you need to convert it to C# DateTime you need convert it manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM