2014-12-28 4 views
0

내 컴퓨터에서 실행되는 가상 서버의 속성을 포함하는 텍스트 파일이 있습니다. VB 2008에서 빌드 된 GUI에서 해당 속성을 편집 할 수 있기를 원합니다. 속성 파일은 기본값으로 미리 생성되어 있으며 필요에 맞게 값을 변경하고 싶습니다. 다음과 같이속성 텍스트 파일 편집 vb.net

등록 정보 파일 포맷 : 내가 필요하면 선택 할 수있다

Item-One=ValueOne 
Item-Two=ValueTwo 
Item-Three=OtherLongValue 
etc. 

재산이의 이름을 기반으로 (항목-두) 다음 원래의 값 (알 수 있습니다 제거) 그리고 내 사용자 지정 값에 배치하십시오. 값은 문자열 유형입니다.

나는 두 가지 제안을 이미 시도했지만 내 목표를 달성하지 못했습니다.

Attempt1: 
System.IO.File.WriteAllText(propName, System.IO.File.ReadAllText(propName).Replace("initial", "final")) 

Attempt2: 
Dim thefile As String = PropertyFileName 
Dim lines() As String = System.IO.File.ReadAllLines(thefile) 
lines(28) = "Item-Example=" + myValue 
System.IO.File.WriteAllLines(thefile, lines) 

숫자 1은 원래 값을 알 필요가 있기 때문에 작동하지 않습니다. 그렇지 않습니다. 2 번은 "작동"하지만 이전 버전을 바꾸는 대신 새 줄을 추가하는 경우가 있습니다.

+2

텍스트 파일이 랜덤 액세스하지 않은 약간의 추가 좋은 출발점이되어야합니다 당신이 그것을 읽을 필요가 그것을 구문 분석을 한 다음 저장 모든 것이 끝나면 돌아온다. INI 스타일 파일처럼 보이므로 구문 분석에 도움이되는 몇 가지 WIN32 함수가 있습니다. – Plutonix

답변

0

다음은 내가 만든 수업입니다.
또한 인텔리 센스와 관련하여 도움이 될 문서화되어 있습니다.
벨로우 (Bellow) 나는 그 사용법의 몇 가지 예를 추가했다.


SettingManager.vb

''' <summary> 
''' Manages Settings which can be loaded and saved to a file specified 
''' </summary> 
''' <remarks></remarks> 
Public Class SettingManager 
    Private filePath As String 
    Private prop As New Dictionary(Of String, String) 

    ''' <summary> 
    ''' Create a new SettingManager and loads settings from file specified. 
    ''' If file specified doesnt exist, a new one is created upon save() 
    ''' </summary> 
    ''' <param name="filePath">Setting file to load</param> 
    ''' <remarks></remarks> 
    Sub New(ByVal filePath As String) 
     Me.filePath = filePath 
     If (Not System.IO.File.Exists(filePath)) Then 
      Return 
     End If 
     Using reader As System.IO.StreamReader = New System.IO.StreamReader(filePath) 
      Dim line As String 
      line = reader.ReadLine() 

      'Loop through the lines and add each setting to the dictionary: prop 
      Do While (Not line Is Nothing) 
       'Spit the line into setting name and value 
       Dim tmp(2) As String 
       tmp = line.Split("=") 
       Me.AddSetting(tmp(0), tmp(1)) 
       line = reader.ReadLine() 
      Loop 
     End Using 
    End Sub 

    ''' <summary> 
    ''' Get value of specified setting if exists. 
    ''' If setting doesnt exist, KeyNotFound exception is thrown 
    ''' </summary> 
    ''' <param name="name">Name of setting</param> 
    ''' <returns>Value of setting</returns> 
    Function GetSetting(ByVal name As String) As String 
     If (Not prop.ContainsKey(name)) Then 
      Throw New KeyNotFoundException("Setting: " + name + " not found") 
     End If 
     Return prop(name) 
    End Function 

    ''' <summary> 
    ''' Adds a new setting. 
    ''' </summary> 
    ''' <param name="name">Name of setting</param> 
    ''' <param name="value">Value of setting</param> 
    ''' <remarks>Save() function should be called to save changes</remarks> 
    Sub AddSetting(ByVal name As String, ByVal value As String) 
     If (prop.ContainsKey(name)) Then 
      prop(name) = value 
     Else 
      prop.Add(name, value) 
     End If 
    End Sub 

    ''' <summary> 
    ''' Saves settings to file. Any new settings added are also saved 
    ''' </summary> 
    ''' <remarks></remarks> 
    Sub Save() 
     Using writer As System.IO.StreamWriter = New System.IO.StreamWriter(filePath) 
      For Each kvp As KeyValuePair(Of String, String) In Me.prop 
       writer.WriteLine(kvp.Key + "=" + kvp.Value) 
      Next 
     End Using 
    End Sub 
End Class 

사용 방법 :

  1. 위의 코드로 SettingManager.vb
  2. 복사라는 프로젝트에 새 파일을 작성하고

사용 예제

Dim sm As New SettingManager("settings.txt") 

'Get Setting 
Console.WriteLine(sm.GetSetting("Item-One")) 'Value-One 

'Change setting 
pm.AddSetting("Item-One", "different_value") 
Console.WriteLine(sm.GetSetting("Item-One")) 'different_value 

'Add new Setting 
pm.AddSetting("name", "Krimson") 
Console.WriteLine(sm.GetSetting("name")) 'Krimson 

'Save any changes made 
sm.Save() 


참고 : 코드는 충분히 강력하지 않다. 예를 들어 값에 =이 있으면이 문제를 방지하기 위해 구현 된 검사가 없기 때문에 오류가 발생할 수 있습니다. 당신이 여기에 문자를 변경하고 캔트 - - 그러나,이

+1

이 작품을 아름답게 조율 해 주셔서 감사합니다. – PCGuy13

0

  Do While (Not line Is Nothing) 
       If line = Nothing OrElse line.Length = 0 OrElse line.StartsWith("#") Then 
        'Continue Do 
       Else 
        'Spit the line into setting name and value 
        Dim tmp(2) As String 
        tmp = line.Split("=") 
        Me.AddSetting(tmp(0), tmp(1)) 

       End If 
       line = reader.ReadLine() 
      Loop 
+1

"약간의 추가"무엇에? @Krimson 응답에 대한 대답은 무엇입니까? 그렇게 명확하게 말하면, SO에 대한 응답은 점수에 따라 재주문 될 수 있습니다. 시간 기반 포럼이나 대화와 같지 않습니다. –