2011-10-17 84 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(); 
    } 
}