在c#中读取随机访问文件

本文关键字:访问 文件 随机 读取 | 更新日期: 2023-09-27 18:11:28

有人知道在c#中是否可以读取随机访问文件吗?

我试图在c#中复制以下函数(从旧的VB6应用程序)-

Open File For Random Shared As #100 Len = Len(Record)
    Get #100, DM, Record
Close #100
Public DM As Long
Public Record As DMrecord
Public Type DMrecord
column1 As Long
column2 As Integer
column3 As Integer
column4 As Integer
column5 As String * 4
End Type

编辑-

我现在已经尝试使用VisualBasic DLL如下所示,并在FileGetObject行收到以下错误-

"最适合Microsoft.VisualBasic.FileSystem的重载方法。FileGetObject(int, ref object, long)有无效参数"

我使用的代码是-

        public class Record 
    {
        public int DMtype;
        public long ecn;

        public Record(int DMtype, long ecn) 
        {
            this.DMtype = DMtype;
            this.ecn = ecn;
        }
        public Record()
        {
        }
    }

string fileName = @"C:'RandomAccess.dat";
        string returnString = string.Empty;
        int row = 1;
        int maxRow = 1000;
        Record aFileRecord = new Record();
        FileSystem.FileOpen(1, fileName, OpenMode.Random, OpenAccess.Read, OpenShare.LockRead);
        while (row < maxRow)
        {
            //Get record 2 1st.>>
            FileSystem.FileGetObject(1, aFileRecord, row);
            returnString += aFileRecord.DMtype.ToString() + "$" + aFileRecord.ecn.ToString();
            row++;
        }
        FileSystem.FileClose(1);

我已经尝试将'Record'设置为结构体和类,并得到相同的错误。

编辑22/08/13 -我从来没有得到这个底部,最终导出随机访问数据到逗号分隔的文本文件在VB6,然后在SSIS消费文件。

在c#中读取随机访问文件

只需添加Microsoft.VisualBasic.dll的引用,并使用FileSystem.FileOpen指定Random打开模式,并使用FileSystem.FileGetObject方法。此行为与VB6中的Open语句和Get关键字相同。