2016-06-15 3 views
0

약 35 개의 텍스트 상자를 포함하는 간단한 WindowsForm 응용 프로그램을 만들려고합니다. 버튼을 눌러 텍스트 파일에 저장하면 원하는 데이터를로드 할 수 있습니다. 프로그램을 시작할 때 데이터를 다시 텍스트 상자에 넣으십시오. 3 가지 주요 문제점이 있습니다. 텍스트 파일로 정보를 기록 할 수있는 가장 좋은 방법을 알아내는C에서 텍스트 파일에 문자열을 쓰거나 읽는 중 #

  1. 어떻게 시작시 파일에서 읽을 수있는 응용 프로그램 루트 디렉터리에있는 경우 텍스트 파일의 경로를 지정하는 방법
  2. (나는 이것이 Form1_Load에서 일어날 것이라고 믿는다.)

나는 그걸로 손을 been다. 각 텍스트 상자에는 변경되지 않는 텍스트 파일의 자체 줄이 있어야합니다. 텍스트 파일도 그래서 만약 이런 종류의 일을 할 수있는 가장 좋은 방법입니다 만약 내가 그런 짓을 할 텍스트를로드하기위한

private void btnSaveCommands_Click(object sender, EventArgs e) 
    { 
     string path = System.IO.Path.GetDirectoryName("commands"); 
     var lines = File.ReadAllLines("commands.txt"); 
     lines[1] = commandTextBox1.Text; 
     lines[2] = commandTextBox2.Text; 
     lines[3] = commandTextBox3.Text; 
     lines[4] = commandTextBox4.Text; 
     lines[5] = commandTextBox5.Text; 
     etc..... (35 times) 
     File.WriteAllLines("commands.txt", lines); 
    } 

....

private void Form1_Load(object sender, EventArgs e) 
    { 
    string path = System.IO.Path.GetDirectoryName("commands"); 
    var lines = File.ReadAllLines("commands.txt"); 
     commandTextBox1.Text = lines[1]; 
     commandTextBox2.Text = lines[2]; 
     etc.... 
    } 

나는 확실하지 않다가 어떤 더 좋거나 더 쉬운 옵션이 있다면 그것들을 언급하십시오.

나는 더 많은 조사를 해본 결과 레지스트리가 작동 할 수 있다는 사실을 발견했습니다. 당신의 TextBox ES에는 고유 한 이름이있는 경우

+0

현재 솔루션의 문제가 무엇인가를 저장하는? DB에 저장하는 것도 고려할 수 있습니다. – Rahul

+0

사용자 환경 설정이나 정적 응용 프로그램 정보를 저장하는 데이 파일을 사용하는 경우 설정 파일을 사용합니다. 어떻게 사용되는지 여기에서 볼 수 있습니다. http://stackoverflow.com/questions/453161/best-practice-to-save-application-settings-in-a-windows-forms-application – Bearcat9425

+0

streamreader 및 streamwriter가 가장 쉬운 방법입니다. – Sherlock

답변

0

당신은

내가 텍스트 파일이 더 나은이 있다면, 그래서 이런 종류의 일을 할 수있는 가장 좋은 방법은 짝수 잘 모르겠어요 작성/쉬운 옵션은 PLZ을 언급 :)

텍스트 파일을 사용할 때 아무 문제가 없습니다. 그러나 .Net은 app.copnfig를 제공하여 응용 프로그램 설정을 저장하고 유지합니다.

프로젝트를 마우스 오른쪽 버튼으로 클릭하고 설정 탭으로 이동하십시오. 필요한 각 설정에 대한 항목을 추가하십시오.예를 들어의 Form_Load

private void Form1_Load(object sender, EventArgs e) 
{ 
    commandTextBox1.Text = Properties.Settings.Default.command1; 
    commandTextBox2.Text = Properties.Settings.Default.command2; 
    etc.... 
} 

에서

Name    Type    Scope    Value 
command1   string    User     test1 
command2   string    User     test2 
additional settings etc 

private void btnSaveCommands_Click(object sender, EventArgs e) 
{ 
    Properties.Settings.Default.command1 = commandTextBox1.Text; 
    Properties.Settings.Default.command2 = commandTextBox2.Text; 
    etc..... (35 times) 
    Properties.Settings.Default.Save(); 
} 
+0

이것은 내가 경험 한 프로그래밍을 통해 가장 간단한 답을 찾은 것입니다. 설정을 설정하고 콘텐츠를 매우 분명하게 가져 오거나 설정하는 방법에 대해 설명했습니다. – Nate

0

, 다음과 같이 뭔가를 할 수 :

public void SaveData(Form form) 
{ 
    var data = form.Controlls 
        .OfType<TextBox>() 
        .ToDictionary(tb => tb.Name, tb => tb.Text); 

    SaveToFile(data); 
} 

public void LoadData(Dictionary<string,string> data, Form form) 
{ 
    var boxes = form.Controlls 
        .OfType<TextBox>() 
        .ToDictionary(tb => tb.Name); 

    foreach(var kvp in data) 
    { 
     boxes[kvp.key].Text = kvp.Value; 
    } 
} 

할을 SaveToFile 쉽게 Newtonsoft.Json 사용할 수있는이 JsonConvert.SerializeObject(dict) 같은 Dictionary<string, string>를 직렬화하고 다시 그걸 얻기 위해 : JsonConvert.Deserialize<Dictionary<string,string>>(data) 파일에 관해서는, 당신이 그것을 읽을 수있는 한 당신이 원하는 어느 곳에서나 저장할 수 있습니다;

1

다음은 런타임에 10 개의 텍스트 상자를 생성하는 작은 예제로, 내용을 파일에 저장하고 나중에 다시로드 할 수 있습니다. 컴파일 타임에 양식 내에 포함되어야하는 유일한 항목은 saveButton이라는 버튼입니다. 구현과 비교하여 배워야 할 중요한 교훈은 텍스트 상자에 액세스하기 위해 35 개의 별도 라인을 반복하지 않는 것입니다. 반복 할 수 있다면 해보십시오.

using System; 
    using System.Collections.Generic; 
    using System.Drawing; 
    using System.IO; 
    using System.Text; 
    using System.Windows.Forms; 

    public partial class Form1 : Form 
    { 
     /// <summary> 
     /// The collection of textboxes that need to be added to the form. 
     /// </summary> 
     private readonly IList<TextBox> inputBoxCollection; 

     /// <summary> 
     /// The name of the file to save the content to. 
     /// </summary> 
     private const string Filename = "textbox-text.txt"; 

     /// <summary> 
     /// Initializes a new instance of the <see cref="Form1"/> class. 
     /// </summary> 
     public Form1() 
     { 
      this.InitializeComponent(); 
      this.inputBoxCollection = new List<TextBox>(); 
      for (var i = 0; i < 10; i++) 
      { 
       this.inputBoxCollection.Add(new TextBox { Location = new Point(0, i*25) }); 
      } 
     } 

     /// <summary> 
     /// Handles the Load event of the Form1 control. 
     /// </summary> 
     /// <param name="sender">The source of the event.</param> 
     /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> 
     private void Form1_Load(object sender, EventArgs e) 
     { 
      var retrievedStrings = File.ReadAllLines(Filename); 
      var index = 0; 
      foreach (var textBox in this.inputBoxCollection) 
      { 
       if (index <= retrievedStrings.Length - 1) 
       { 
        textBox.Text = retrievedStrings[index++]; 
       } 

       this.Controls.Add(textBox); 
      } 
     } 

     /// <summary> 
     /// Handles the Click event of the saveButton control. When pressed, the 
     /// content of all the textboxes are stored in a file called textbox-text.txt. 
     /// </summary> 
     /// <param name="sender">The source of the event.</param> 
     /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> 
     private void saveButton_Click(object sender, EventArgs e) 
     { 
      var builder = new StringBuilder(); 
      foreach (var textBox in this.inputBoxCollection) 
      { 
       builder.AppendLine(textBox.Text); 
      } 

      File.WriteAllText(Filename, builder.ToString()); 
     } 
    } 
} 

콘텐츠를 파일로 저장하는 것이 좋습니다. 데이터베이스와 레지스트리는 줄무늬로 뒤덮 였지만이 응용 프로그램에서는 디스크의 간단한 텍스트 파일이 이상적입니다. 쉽게 완료되고 유지 보수가 쉽습니다.

+0

이 텍스트 파일은 응용 프로그램 루트 디렉토리에 있습니다. – Nate

+0

또한 양식을로드 할 때 새 텍스트 상자를 만드는 대신 기존 텍스트 상자를 어떻게 사용합니까? – Nate

+0

이 경우 파일은 .exe 옆에 생성됩니다. 따라서 Visual Studio에 있다면 디버그/릴리스 내에서 찾을 수 있습니다. 다른 위치에 배치하려면 경로를 지정해야합니다. – BlackBox

관련 문제