2011-10-17 119 views
3

我有兩個csv文件。在第一個文件中,我有一個用戶列表,而在第二個文件中,我有一個重複用戶列表。我試圖刪除第一個文件中等於第二個文件的行。c#從csv中刪除行

繼承人的代碼我迄今爲止:

StreamWriter sw = new StreamWriter(path3); 
     StreamReader sr = new StreamReader(path2); 

     string[] lines = File.ReadAllLines(path); 

     foreach (string line in lines) 
     { 
      string user = sr.ReadLine(); 

      if (line != user) 
      { 
       sw.WriteLine(line); 

      } 

文件1例如:

Modify,ABAMA3C,Allpay - Free State - HO,09072701 

Modify,ABCG327,Processing Centre,09085980 

文件2實施例:

Modify,ABAA323,Group HR Credit Risk & Finance 

Modify,ABAB959,Channel Sales & Service,09071036 

任何建議?

謝謝。

+1

請提供示例文件格式你的帖子... –

+1

你的代碼看起來不完整,你需要關閉你的foreach循環並關閉你的StreamWriter/Reader –

+0

看起來也像功課。標記爲,如果您反對,請隨時更改。 – Polynomial

回答

2

所有你需要做的就是改變在下面的代碼下面的文件路徑和你將得到一個文件(文件一),而文件2中沒有重複的用戶。編寫這段代碼的想法是你想要一些容易理解的東西。當然還有其他更優雅的解決方案,但我想讓它作爲基本的可能你:

(在你的程序的主要方法粘貼此)

 string line; 
     StreamReader sr = new StreamReader(@"C:\Users\justin\Desktop\texts\First.txt"); 

     StreamReader sr2 = new StreamReader(@"C:\Users\justin\Desktop\texts\Second.txt"); 

     List<String> fileOne = new List<string>(); 
     List<String> fileTwo = new List<string>(); 

     while (sr.Peek() >= 0) 
     { 
      line = sr.ReadLine(); 
      if(line != "") 
      { 
       fileOne.Add(line); 
      } 
     } 
     sr.Close(); 
     while (sr2.Peek() >= 0) 
     { 
      line = sr2.ReadLine(); 
      if (line != "") 
      { 
       fileTwo.Add(line); 
      } 
     } 
     sr2.Close(); 
     var t = fileOne.Except(fileTwo); 

     StreamWriter sw = new StreamWriter(@"C:\Users\justin\Desktop\texts\First.txt"); 

     foreach(var z in t) 
     { 
      sw.WriteLine(z); 
     } 
     sw.Flush(); 
0

這個正確關閉流:

using(var sw = new StreamWriter(path3)) 
using(var sr = new StreamReader(path2)) 
{ 
    string[] lines = File.ReadAllLines(path); 

    foreach (string line in lines) 
    { 
     string user = sr.ReadLine(); 

     if (line != user) 
     { 
      sw.WriteLine(line); 
     } 
    } 
} 

的幫助上去除的真正邏輯或比較,回答上面的El Ronnoco的評論...

0

您需要關閉流或利用使用條款

sw.Close(); 

using(StreamWriter sw = new StreamWriter(@"c:\test3.txt")) 
0

您可以使用LINQ ...

class Program 
{ 
    static void Main(string[] args) 
    { 
     var fullList = "TextFile1.txt".ReadAsLines(); 
     var removeThese = "TextFile2.txt".ReadAsLines(); 

     //Change this line if you need to change the filter results. 
     //Note: this assume you are wanting to remove results from the first 
     //  list when the entire record matches. If you want to match on 
     //  only part of the list you will need to split/parse the records 
     //  and then filter your results. 
     var cleanedList = fullList.Except(removeThese); 

     cleanedList.WriteAsLinesTo("result.txt"); 
    } 
} 
public static class Tools 
{ 
    public static IEnumerable<string> ReadAsLines(this string filename) 
    { 
     using (var reader = new StreamReader(filename)) 
      while (!reader.EndOfStream) 
       yield return reader.ReadLine(); 
    } 

    public static void WriteAsLinesTo(this IEnumerable<string> lines, string filename) 
    { 
     using (var writer = new StreamWriter(filename) { AutoFlush = true, }) 
      foreach (var line in lines) 
       writer.WriteLine(line); 
    } 
} 
2

如果這不是功課,但生產的東西,你可以安裝組件,如果你收起你的驕傲,你會節省3小時,您的生活,並使用了一塊VB庫:

有許多例外(逗號之間的CR/LF =引號中的合法;不同類型的報價;等等)這將處理任何excel將導出/導入。

示例代碼加載從程序拉到一個「人」類我把它用在:

Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser(CSVPath) 

     Reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited 
     Reader.Delimiters = New String() {","} 
     Reader.TrimWhiteSpace = True 
     Reader.HasFieldsEnclosedInQuotes = True 

     While Not Reader.EndOfData 
      Try 
       Dim st2 As New List(Of String) 
       st2.addrange(Reader.ReadFields()) 
       If iCount > 0 Then ' ignore first row = field names 
        Dim p As New Person 
        p.CSVLine = st2 
        p.FirstName = st2(1).Trim 
        If st2.Count > 2 Then 
         p.MiddleName = st2(2).Trim 
        Else 
         p.MiddleName = "" 
        End If 
        p.LastNameSuffix = st2(0).Trim 
        If st2.Count >= 5 Then 
         p.TestCase = st2(5).Trim 
        End If 
        If st2(3) > "" Then 
         p.AccountNumbersFromCase.Add(st2(3)) 
        End If 
        While p.CSVLine.Count < 15 
         p.CSVLine.Add("") 
        End While 
        cases.Add(p) 
       End If 
      Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException 
       MsgBox("Line " & ex.Message & " is not valid and will be skipped.") 
      End Try 
      iCount += 1 
     End While 
    End Using 
0
using(var sw = new StreamWriter(path3)) 
using(var sr = new StreamReader(path)) 
{ 
    string []arrRemove = File.ReadAllLines(path2); 
    HashSet<string> listRemove = new HashSet<string>(arrRemove.Count); 
    foreach(string s in arrRemove) 
    { 
     string []sa = s.Split(','); 
     if(sa.Count < 2) continue; 
     listRemove.Add(sa[1].toUpperCase()); 
    } 

    string line = sr.ReadLine(); 
    while(line != null) 
    { 
     string []sa = line.Split(','); 
     if(sa.Count < 2) 
      sw.WriteLine(line); 
     else if(!listRemove.contains(sa[1].toUpperCase())) 
      sw.WriteLine(line); 
     line = sr.ReadLine(); 
    } 
}