2012-07-11 36 views
-2

我需要一個簡單的C#程序,我可以傳遞一個目錄,然後它將遍歷所有文件夾/子文件夾遞歸檢查.nfo文件。函數解析信息並創建新文件

它需要檢查以下標籤中的每個文件NFO,並拉出的唯一ID:

<id>xx234567890</id> 

的XX將字母字符,其餘的數字。

然後它會創建一個包含在同一文件夾單行的「info.nfo」文件: http://powerhostcrm.com/id/(id#從上面)

因此,如果ID是sy1234567890它會創建一個文件: http://powerhostcrm.com/id/sy1234567890

老實說,如果這可以作爲Windows批處理文件或其他更容易完成,那很好。

+1

SOOOO之間搜索代碼...你嘗試過什麼? – 2012-07-11 21:37:54

+0

會''xx234567890'是.nfo文件的標題還是在? – Borophyll 2012-07-11 21:45:32

+0

您的要求不明確。數字值234567890在每個NFO文件中總是相同,或者只是一個9位數字模式,後跟一個空格,並且前面有兩個文本字符? – Steve 2012-07-11 21:52:07

回答

2

該代碼使用正則表達式來<ID>

string[] filesNFO = Directory.GetFiles(@".\", "*.nfo", SearchOption.AllDirectories); 
Regex rx = new Regex(@"<id>[A-Za-z]{2}\d+\</id>" 
foreach(string file in filesNFO) 
{ 
    using(StreamReader sr = File.OpenText(file)) 
    { 
     string content = sr.ReadToEnd(); 
     var m = rx.Matches(content); 
     if(m.Count > 0) 
     { 
      using(StreamWriter sw = new StreamWriter("info.nfo", true)) 
      { 
       sw.WriteLine("http://powerhostcrm.com/" + m[0].ToString().TrimStart("<id>").TrimEnd("</id>"); 
      } 
     } 
    } 
} 
+0

謝謝史蒂夫,會給你一槍! – Dizzy49 2012-07-11 23:00:45

+0

獲取一對錯誤。簡單的我固定,但我得到'參數1:不能從'System.IO.StreamReader'轉換爲'字符串' '名字'r'在當前上下文中不存在'我認爲這應該是' rx'而不是'r' 'System.Text.RegularExpressions.Regx'是一個'類型',但像'變量'一樣使用 – Dizzy49 2012-07-11 23:14:42

+0

@ Dizzy49一些修正添加到上面的代碼中。 – Steve 2012-07-12 07:28:27

2
var files = new DirectoryInfo("Your path").GetFiles("*.nfo", SearchOption.AllDirectories); 
foreach(var file in files) 
{ 
    using(var r = new StreamReader(file.OpenRead())) 
    { 
     string content = r.ReadToEnd(); 
     if(content.Contains("234567890")) 
     { 
      string id = content.Substring(content.IndexOf("234567890") - 2, 11); 
      using(var w = new StreamWriter("info.nfo", true)) // true for append 
      { 
       w.WriteLine("http://powerhostcrm.com/" + id); 
      } 
     } 
    } 
} 

東西沿着這些線。 Lemme知道它是否不起作用。

+0

StreamReader也實現了IDisposable ...但是我相信'File.ReadAllText(...)'會是更好的選擇。 – 2012-07-11 21:53:33

+0

@AustinSalonen,你是對的,它更緊湊。儘管如此,不要認爲OP實際上關心的代碼很髒。 – Dmitriy 2012-07-11 21:57:11

+0

很酷。請注意,這裏有一組用戶在StreamReader未正確處理的情況下降低了答案。 – 2012-07-11 21:59:25