2011-09-27 5 views
3

방금 ​​C#을 배우기 시작했고 Minecraft 실행기에 대한 간단한 구성 파일 생성기를 무언가와 같이 만들었습니다. Visual C# 2010에서 응용 프로그램을 독립적으로 실행하려고 할 때 문제가 발생했습니다. "인덱스 및 길이는 문자열 내의 위치를 ​​참조해야합니다. 매개 변수 이름 : 길이" 첫 번째 실행시 (빈 텍스트 파일이 만든 후) "인덱스가 배열 범위를 벗어났습니다" 다음에이 인덱스를 다시 시작하면 인덱스가 벗어났습니다.IDE 외부에서 실행될 때 "인덱스가 배열의 경계를 벗어났습니다"

왜 이런 일이 일어나고 있는지 혼란 스럽습니다. 줄 번호를 알려주지 않고 IDE를 통해 응용 프로그램을 실행하지 않을 때만 발생합니다 (디버그 빌드를 실행하든 릴리스 빌드를 실행하든).). 어떤 도움이라도 대단히 감사합니다. 아마도 끔찍한 코딩에 대해 사과드립니다. 저는이 언어의 초보자입니다.

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace Minecraft_Launcher_Config 
{ 

    public partial class mcwindow : Form 
    { 

     private void outputText(string outtext) 
     { 
      output.Text = outtext; 
     } 

     private string encrypt(string text, int key) 
     { 
      string newText = ""; 

      for (int i = 0; i < text.Length; i++) 
      { 
       int charValue = Convert.ToInt32(text[i]); 
       charValue ^= key; 

       newText += char.ConvertFromUtf32(charValue); 
      } 

      return newText; 
     } 
     public mcwindow() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      string iuser = ""; 
      string ipass = ""; 
      string imem = "1024"; 
      string iserver = ""; 
      if (System.IO.File.Exists("config.cfg")) 
      { 
       System.IO.StreamReader configFile = 
       new System.IO.StreamReader("config.cfg"); 
       string[] iconfig = System.IO.File.ReadAllLines("config.cfg"); 
       iuser = iconfig[0]; 
       ipass = iconfig[1]; 
       imem = iconfig[2]; 
       iserver = iconfig[3]; 
       configFile.Close(); 
       outputText("Successfully loaded and decrypted config!"); 
      } else 
      { 
       System.IO.StreamWriter configwrite = new System.IO.StreamWriter("config.cfg"); 
       configwrite.Close(); 
       outputText("Welcome to Frohman's Minecraft Launcher Config!"); 
      } 

      username.Text = iuser; 
      memselect.Value = int.Parse(imem); 
      int OKey = Convert.ToInt32(username.Text.Substring(0, 1)); 
      string unenpassword = encrypt(ipass, OKey); 
      password.Text = unenpassword; 
     } 

     private void label1_Click(object sender, EventArgs e) 
     { 

     } 

     private void label4_Click(object sender, EventArgs e) 
     { 

     } 

     private void saveexit_Click(object sender, EventArgs e) 
     { 
      if (username.Text != "" & password.Text != "") 
      { 
       outputText("Saving and exiting!"); 
       int IKey = Convert.ToInt32(username.Text[0]); 
       string enpassword = encrypt(password.Text, IKey); 
       string outString = username.Text + System.Environment.NewLine + enpassword + System.Environment.NewLine + memselect.Value + System.Environment.NewLine + serverip.Text; 
       System.IO.StreamWriter configwrite = new System.IO.StreamWriter("config.cfg"); 
       configwrite.WriteLine(outString); 
       configwrite.Close(); 
       System.Threading.Thread.Sleep(150); 
       Environment.Exit(0); 
      } 
      else 
      { 
       outputText("You're missing some data!"); 
      } 
     } 

     private void password_TextChanged(object sender, EventArgs e) 
     { 

     } 

    } 
} 
+0

'config.cfg' 파일에 4 줄이 있는지 확인하십시오. – Reniuz

+0

그건 그렇고. 디버그 구성을 사용하여 프로젝트를 빌드하면 예외 라인 정보를 얻는 데 도움이됩니다. – MichaelMocko

답변

2

이 코드 :

string[] iconfig = System.IO.File.ReadAllLines("config.cfg"); 
    iuser = iconfig[0]; 
    ipass = iconfig[1]; 
    imem = iconfig[2]; 
    iserver = iconfig[3]; 

... 당신이 파일이 4 개 라인보다 적은 포함 된 경우에 대해 이야기 한 예외가 발생합니다. 그게 무슨 일이야, 아마? (공백 파일을 만드는 것에 대해 이야기 해보십시오.)

StreamReader으로 파일을 여는 것이지만, 목적이 없으면 별도로 열리는 ReadAllLines으로 전화를 걸면이 파일을 엽니 다. ... 어떤 바꿈을 포함하지 않는 outString 가정,

System.IO.StreamWriter configwrite = new System.IO.StreamWriter("config.cfg"); 
configwrite.WriteLine(outString); 
configwrite.Close(); 

만 한 줄을 쓰고 그래서 방법이 을 할 수 확실하지 않다 :이 코드 파일을 쓰기

심지어 IDE에서 이제까지 일.)

(당신이 경우 파일 핸들이 닫혀 가도록 (듯이) exce이있는 경우에도 StreamReaderStreamWriter, 당신은 using 문을 사용해야합니다 사용하고자합니다 . 당신이 File.WriteAllLines 또는 File.WriteAllText를 사용할 수 있습니다)

마지막으로, 암호화 하지은 텍스트를 통해 수행해야합니다 - 당신은 여기에 있지만 StreamReader 또는 StreamWriter를 사용할 필요가 없습니다.. 일반적으로 잘못된 코드 단위 등을 쉽게 포함 할 수있는 깨진 텍스트로 끝날 것입니다. 일반적으로 텍스트를 암호화하려면 이진으로 변환하고 표준 암호화 알고리즘을 적용한 다음 (직접 작성하지 마십시오) 그것을 밖으로 텍스트를 원한다면, 당신은 Convert.ToBase64String와 base64로 변환합니다.당신이 이미

string[] iconfig = System.IO.File.ReadAllLines(@"MyPath\config.cfg"); 

처럼 전체 경로와 구성 파일을로드 할 수 File.readAllLines.

시도를 파일을 닫고 방법 것이 불가능 할 수 File.ReadAllLines 를 사용한 경우 모두의

+0

의견을 보내 주셔서 감사합니다. 4 줄 미만의 문제는 상당히 가능성이 있습니다. 나는 그것이 간과 된 것처럼 보입니다. 읽기 및 쓰기 방법의 혼란은 다양한 방법을 테스트하는 끔찍한 결과였습니다. 그것이 가치있는 일이라면 출력 텍스트에 줄 바꿈이 포함되지만, 나는 아무 데서도 한 줄 더 추가 될 것입니다. 간단한 암호화는 다시 테스트였습니다. 정보를 제공해 주셔서 감사합니다! 매우 도움이된다! – Frohman

1

먼저 StreamReader를 사용하지 말아 확실 할 것보다

if(iconfig.length >= 4) 
    //Proceed With Config 

그리고 마지막으로 우리를 원한다면
가 시작 인덱스 플러스 길이는이 인스턴스 내에서 위치를 나타냅니다 경우 ArgumentOutOfRangeException을 throw합니다 Application.Setting

+0

고마워요! 나는 지금 그들이보고있는 파일 읽기 메커니즘을 정리하고있다. 경로에 관해서 - config 파일이 .exe 바로 옆의 다른 위치가 될 수 없었습니다. – Frohman

+1

@Frohman 그것은 당신이 .exe 일 수 있으며 "/config.cfg"로 액세스해야합니다. 그렇지 않으면 일부 시스템은 config.cfg를 검색하거나 시스템 변수가 구성된 config.cfg 파일을 사용하기 시작합니다. – Burimi

+0

그래, 고마워! – Frohman

0

String.SubString를 사용하는 것보다 전자의 구성.

iuser=""; 
    ... 
    username.Text = iuser; 
    memselect.Value = int.Parse(imem); 
    int OKey = Convert.ToInt32(username.Text.Substring(0, 1)); 

username.Text.Substring (0, 1) 빈 문자열이있는 경우 외부 배열의 경계입니다 : 처음 실행시

는이 코드를 호출합니다.

관련 문제