1

Input: I have .csv file with n columns in it. First row is a header. I need to calculate sum of one the fields in .csv file (for example it's called "Value") and then calculate hashsum of this sum, using SHA1.

I see that SHA1 can work with string http://snipplr.com/view/70294/ But how canI combine that with data from .csv file? Could you please help me on that.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • What is it you're having trouble with _exactly_? As you can see in the **Related** column, there are quite some [questions](http://stackoverflow.com/questions/2081418/parsing-csv-files-in-c-sharp?rq=1) about reading CSV files. You usually read this data as strings, which you can pass to the code you found. – CodeCaster Feb 13 '14 at 11:09
  • Have troubles with combining both in one working code. – user3305630 Feb 13 '14 at 11:16
  • Then show what you've got. – CodeCaster Feb 13 '14 at 11:17

1 Answers1

1

A basic way of doing it would be:

  • Read the CSV File
  • Sum the values
  • Pass the ToString value to SHA-1
public static string GetSha1Sum()
{
     double sum = 0;
     using (CSVReader cr = new CSVReader(myfilename))
     {
         foreach (string[] line in cr)
         {
             //assuming your field is the first: 
             sum += Convert.ToDouble(line[0]);
         }
     }
     SHA1 sha1Hash= SHA1.Create();
     byte[] data = sha1Hash.ComputeHash(Encoding.UTF8.GetBytes(sum.ToString()));
     string digest = HexDigest(data);
 }

The HexDigest helper is a function that format a byte array into hex string:

public static string HexDigest(byte[] data)
{
    StringBuilder sBuilder = new StringBuilder();
    for (int i = 0; i < data.Length; i++)
    {
        //format the bytes in hexadecimal
        sBuilder.Append(data[i].ToString("x2"));
    }
    return sBuilder.ToString();
}

More information about the CSVReader

artragis
  • 3,677
  • 1
  • 18
  • 30