2016-08-14 3 views
1

난과 같이 번호가 .txt 파일이 들어있는 폴더가 :C# : 폴더의 다음 파일을 읽는 중?

0.txt 
1.txt 
... 
867.txt 
... 

내가 내가 그 폴더에 다음 파일의 내용을 반환 할 때마다 readNextFile();가 호출되는 일을하려고하고, 마지막으로 읽은 파일 다음에 파일이 없으면 return string.Empty;입니다. 누르면 버튼을 누르면 프로그램이 다음 파일을 읽고 내용을 채우게됩니다. 버튼 누름간에 파일이 변경 될 수 있습니다. 내가 전에 이런 짓을하는 방법이이었다 :

0.txt 
1.txt 
5.txt 
6.txt 
... 

2.txt이 존재하지 않기 때문에 분명히 1.txt에 박히면서 것 :

int lastFileNumber = 0; 

string readNextFile() 
{ 
    string result = string.Empty; 
    //I know it is recommended to use as few of these as possible, this is just an example. 
    try 
    { 
     string file = Path.Combine("C:\Somewhere", lastFileNumber.ToString() + ".txt"); 
     if (File.Exists(file)) 
     { 
      result = File.ReadAllText(file); 
      lastFileNumber++; 
     } 
    } 
    catch 
    { 

    } 
    return result; 
} 

문제는 가끔 이런 종류의 상황이있을 수있다. 다음 기존 파일로 건너 뛰고 그 파일을 읽어야합니다. 그리고 파일 이름이 Padded가 아니기 때문에 알파벳 배열로 파일 이름을 문자열 배열로 정렬 할 수 없으므로 일 수 있습니다. 따라서 파일 이름이 Padded가 아니므로 1.txt 바로 뒤에 1000000000.txt이 읽혀집니다.

어떻게하면 될까요?

답변

3

linq을 사용하여 저장된 번호를 기반으로 다음 파일을 확인할 수 있습니다. 파일 이름을 정수 표현으로 변환하여 파일을 주문한 후에 수행됩니다.

int lastFileNumber = -1; 
bool isFirst = true; 
private void buttonNext_Click(object sender, EventArgs e) 
{ 
    int lastFileNumberLocal = isFirst ? -1 : lastFileNumber; 
    isFirst = false; 
    int dummy; 
    var currentFile = Directory.GetFiles(@"D:\", "*.txt", SearchOption.TopDirectoryOnly) 
          .Select(x => new { Path = x, NameOnly = Path.GetFileNameWithoutExtension(x) }) 
          .Where(x => Int32.TryParse(x.NameOnly, out dummy)) 
          .OrderBy(x => Int32.Parse(x.NameOnly)) 
          .Where(x => Int32.Parse(x.NameOnly) > lastFileNumberLocal) 
          .FirstOrDefault(); 

    if (currentFile != null) 
    { 
     lastFileNumber = Int32.Parse(currentFile.NameOnly); 

     string currentFileContent = File.ReadAllText(currentFile.Path); 
    } 
    else 
    { 
     // reached the end, do something or show message 
    } 
} 
+0

읽는 동안 파일을 추가 할 필요가 없다고하셨습니다. 문제는 버튼을 누르면 프로그램이 다음 파일을 읽고 그 내용으로 물건을 만드는 것입니다. – user152356

+0

@ user152356 그래서 어디에 문제가 있습니다. 쓰기를 읽는 동안 파일이 생성되지 않습니까? – user3185569

+0

질문 편집 : 버튼을 누르면 프로그램이 다음 파일을 읽고 내용으로 채워 넣을 수있는 버튼을 갖고 싶습니다. 버튼 누름간에 파일이 변경 될 수 있습니다. – user152356

0

전체 파일 목록을 먼저 얻지 않고 마지막으로 어떤 파일을 찾을 수 있다고 생각하지 않습니다. 정렬은 파일 이름 길이별로 정렬 한 다음 파일 이름별로 정렬하여 단순화 할 수 있습니다.

int currentFileNumber = -1; 
string currentFileName; 
string currentFileText; 
string[] allFileNames; 

string readCurrentFile() 
{ 
    try 
    { 
     if (allFileNames == null) allFileNames = (
       from f in Directory.EnumerateFiles(@".", "*.*") 
       orderby f.Length, f select f).ToArray(); 

     currentFileNumber++; 

     if (currentFileNumber >= allFileNames.Length) return null; // no files left 

     currentFileName = allFileNames[currentFileNumber]; 

     currentFileText = File.ReadAllText(currentFileName); 

     return currentFileText; 
    } 
    catch (Exception ex) { 
     MessageBox.Show(ex.Message); 
     return readCurrentFile(); // get next file if any Exception 
    } 
}