aneilg
asked on
Removes Rows in a CSV FIle
I am using SSIS Script Task Editor C#
I have a csv file and I need to delete extra rows that are not needed.
Example:- 9 columns.
Number – Date – ect.
I can have any number of rows.
Then an empty row.
Then unwanted data.
So basically I want to delete all rows after the first empty row.
I have a csv file and I need to delete extra rows that are not needed.
Example:- 9 columns.
Number – Date – ect.
I can have any number of rows.
Then an empty row.
Then unwanted data.
So basically I want to delete all rows after the first empty row.
ASKER
thanks i'll give it a go.
If the file is small, then you can load the whole thing into memory, remove the unwanted entries, then overwrite the original without using a temporary file:
string FileName = @"C:\Users\Mike\Documents\SomeFile.txt";
List<string> lines = new List<string>(System.IO.File.ReadAllLines(FileName));
int blankLine = lines.FindIndex(x => x.Trim().Length == 0);
if (blankLine != -1)
{
while(lines.Count > blankLine)
{
lines.RemoveAt(lines.Count - 1);
}
}
System.IO.File.WriteAllLines(FileName, lines.ToArray());
ASKER
Thanks Barry.
Just a little change works perfect.
Just a little change works perfect.
ASKER
I've requested that this question be closed as follows:
Accepted answer: 0 points for aneilg's comment #a40562034
for the following reason:
Perfect.
Accepted answer: 0 points for aneilg's comment #a40562034
for the following reason:
Perfect.
Hi Aneilg
Please let us know if you are going to accept solutions and award points for this.
I think you should possibly split points between myself and Mike Tomlinson as we both gave you good approaches, each with their own merits.
Thank you
Please let us know if you are going to accept solutions and award points for this.
I think you should possibly split points between myself and Mike Tomlinson as we both gave you good approaches, each with their own merits.
Thank you
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
One approach may be to use StreamReader and StreamWriter objects in C# in the SSIS Script Task.
With the StreamReader object read the file line by line writing each line out to a temporary file with the StreamWriter object.
Skip(do not write out lines that should be excluded)
In your case, if a given line just read is an empty string, then you can exit the loop
Then copy the clean temp file back over the original file
The following is sample code which you can adapt - the file is passed in as an SSIS variable
Open in new window