2012-11-15 22 views
0

我需要將一段代碼從VB轉換爲C#。我應該用什麼來代替FileSystemObject和TextStream?轉換文件讀取VB代碼到C#

下面的代碼所做的是讀取已存在於目錄中的文件,並將該文件的內容添加到字段中。

Private Sub Read_abc_File() 
    Dim FileSystem As FileSystemObject 
    Dim abcFile As TextStream 
    Dim abcLine As String, abcSection As String 
    Dim abcFilename As String 
    Const Read As Integer = 1 

    abcFilename = "abc.txt" 


    Set FileSystem = New FileSystemObject 

    If Not FileSystem.FileExists(abcFilename) Then 
     FileSystem = Null 
     Exit Sub 
    End If 

    Set abcFile = FileSystem.OpenTextFile(abcFilename, Read, False) 

    Do While abcFile.AtEndOfStream <> True 
     abcLine = abcFile.ReadLine 

     If abcLine > " " Then 
      If Left$(abcLine, 1) = "[" Then 
       abcSection = abcLine 
      Else 
       Select Case abcSection 
        Case "[Datafiles]" 
         DataFilename.AddItem abcLine 
        Case "[Locations]" 
         Location.AddItem abcLine 
        Case "[Formats]" 
         Format.AddItem abcLine 
        Case "[Categories]" 
         Category.AddItem abcLine 
       End Select 
      End If 
     End If    
    Loop 

    abcFile.Close 
    Set abcFile = Nothing 
    Set FileSystem = Nothing 
End Sub 

任何建議/答案表示讚賞。

謝謝!

+2

這似乎不像VB.NET代碼。如果這是VB6代碼,請添加一個'VB6'標籤。 – decyclone

回答

0

繼承人一個代碼片段,讓你開始,我認爲你應該能夠完成這項工作。

using System; 
using System.IO; 

static void Main(string[] args) 
{ 
    string fileName = "abc.txt"; 

    if (!File.Exists(fileName)) 
     return; 

    using (FileStream file = File.OpenRead(fileName)) 
    using (StreamReader reader = new StreamReader(file)) 
    { 
     while (!reader.EndOfStream) 
     { 
      string line = reader.ReadLine(); 
     } 
    } 
}