1

My problem is simple yet complex. I'm a SQL DB Developer that now has to create an SSIS package with C# code in it. The code needs to do a few things but the components I'm having a problem with are:

  1. Reading the last line in the text file and inserting that line into columns in a SQL table.
  2. Each of the detail rows from the 2nd row to the 2nd last row need to be inserted into another table.

I'm relatively new to C# and have NO idea how to go about this. Can someone please guide me in the right direction?

0

2 Answers 2

3

How big is the file? If you can read it all into memory, it'll make life a lot simpler:

string[] lines = File.ReadAllLines("file.txt");

// Could use lines[lines.Length - 1] but LINQ makes it simpler...
string lastLine = lines.Last();

IEnumerable<string> otherLines = lines.Skip(1).Take(lines.Length - 2);

So that's the "getting the data out of a file" part. For the database part, you haven't really given us enough information to help you. You need to determine how you're going to do database access (straight ADO.NET, LINQ etc) and then read tutorials on that topic. There are plenty around.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help. This is pointing me in the right direction already. As to how I'm going to access the DB, I am not sure yet. I first need to figure out how to I suppose extract the data, etc, before I'm going to break my head over the rest. Thanks for responding this quick!
0

Try this found it online for you

public static String ReadLastLine(string path)
{
    return ReadLastLine(path, Encoding.ASCII, "\n");
}

public static String ReadLastLine(string path, Encoding encoding, string newline)
{
    int charsize = encoding.GetByteCount("\n");
    byte[] buffer = encoding.GetBytes(newline);
    using (FileStream stream = new FileStream(path, FileMode.Open))
    {
        long endpos = stream.Length / charsize;
        for (long pos = charsize; pos < endpos; pos += charsize)
        {
            stream.Seek(-pos, SeekOrigin.End);
            stream.Read(buffer, 0, buffer.Length);
            if (encoding.GetString(buffer) == newline)
            {
                buffer = new byte[stream.Length - stream.Position];
                stream.Read(buffer, 0, buffer.Length);
                return encoding.GetString(buffer);
            }
        }
    }
    return null;
}

http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/ff6c07e2-9c36-4490-a989-f24dcff76145

4 Comments

Thanks, John. I'm definitely going to look into this!
No thnx, Is stukken sneller, its way faster ;)
What kind of database do you have to connect to?
I need to connect to a SQL 2008 DB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.