Home   Subscribe   Linkedin
  Archive Contact  

Read and write *.csv File in C#

The following example demonstrates how to Read and write *.csv File.

Read *.csv File:

internal static TableData ReadCsvFile(string filePath) 
       { 
           if (!File.Exists(filePath)) return null;

           var fileExtention = Path.GetExtension(filePath); 
           if (fileExtention != ".csv") return null;

           var table = new TableData 
           { 
               DataColumns = new List<string>(), 
               DataRows = new List<Dictionary<string, object>>() 
           };

           try 
           { 
               var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath.Substring(0, filePath.LastIndexOf('\\')) + 
                                              ";Extended Properties='text;HDR=yes;FMT=Delimited;'";

               using (var connection = new OleDbConnection(connectionString)) 
               { 
                   connection.Open();

                   var restriction = new[] { null, null, ConvertNormalToOledbString(Path.GetFileName(filePath)), null }; 
                   var workSheetNamesDataTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, restriction); 
                   if (workSheetNamesDataTable == null) 
                   { 
                       return null; 
                   } 
                   var dataRow = workSheetNamesDataTable.Rows.Cast<DataRow>().Where(workSheet => workSheet != null).FirstOrDefault(); 
                   var sheetName = dataRow["TABLE_NAME"].ToString();

                   var query = "select * from [" + sheetName + "]"; 
                   var dataSet = new DataSet();

                   using (var dataAdapter = new OleDbDataAdapter(query, connection)) 
                   { 
                       var dTable = new DataTable(sheetName); 
                       dataAdapter.Fill(dTable); 
                       dataSet.Tables.Add(dTable); 
                   } 
                   var rows = dataSet.Tables[0].Rows; 
                   table.TableName = sheetName; 
                   foreach (DataColumn column in dataSet.Tables[0].Columns) 
                   { 
                       table.DataColumns.Add(column.ColumnName); 
                   } 
                   var columnCount = table.DataColumns.Count; 
                   foreach (DataRow row in rows) 
                   { 
                       var newRow = new Dictionary<string, object>(); 
                       for (var i = 0; i < columnCount; i++) 
                       {

                           newRow.Add(table.DataColumns[i], row[table.DataColumns[i]]); 
                       } 
                       table.DataRows.Add(newRow); 
                   } 
                   connection.Close(); 
               } 
           } 
           catch 
           {


           } 
           return table; 
       } 
       private static string ConvertNormalToOledbString(string str) 
       { 
           str = str.Replace('.', '#'); 
           str = str.Replace('[', '('); 
           str = str.Replace(']', ')'); 
           return str; 
       }


Write *.csv File:

internal static void CreateCsvFile(TableData tableData, string directoryPath) 
        { 
            if(tableData==null || tableData.DataColumns==null || tableData.DataColumns.Count<=0 
               || tableData.DataRows==null || tableData.DataColumns.Count<=0) 
            return; 
            if (!Directory.Exists(directoryPath)) 
                Directory.CreateDirectory(directoryPath); 
            var fileName = Guid.NewGuid().ToString() + ".csv"; 
            var fileStream = File.Create(directoryPath + fileName);

            using (var writer = new CsvFileWriter(fileStream)) 
            { 
                //Write Header Row 
                var headerRow = new CsvRow(); 
                headerRow.AddRange(tableData.DataColumns.Select(t => String.Format(t))); 
                writer.WriteRow(headerRow);

                //Write value Row 
                foreach (var t1 in tableData.DataRows) 
                { 
                    var row = new CsvRow(); 
                    row.AddRange(tableData.DataColumns.Select((t, j) => String.Format(t1[tableData.DataColumns[j]].ToString()))); 
                    writer.WriteRow(row); 
                } 
              
            } 
        }

 

 I have attached the sample application along with this post

ReadandwriteCsvFile.zip (23.02 kb)

Posted by: Mohd Ishaq

Categories: C#, Console Application

Tags:

How to Split Multi-page Tiff Image to multiple Images in C#.

In this example we will see that how we can break Multi Page Tiff Image to separate series of images.

Steps of conversion:

1) Create a new console application in Visual Studio 2010.

1

2) Define your input tiff file location and output images location. It should be something like this

static void Main(string[] args)
      {

          string inputTiffFileName = @"C:\Users\Ahmed\Desktop\MultipageTIFImage.tif";
          string outputLocation = @"C:\Users\Ahmed\Desktop\";
          

      }

3) Now make a method which breaks tiff separate images and call it from Main.

static void TiffToImage(string inputTiffFileName, string outputLocation)
       {
           var imageFile = Image.FromFile(inputTiffFileName);
           var frameDimensions = new FrameDimension(imageFile.FrameDimensionsList[0]);
           var numberOfFrames = imageFile.GetFrameCount(frameDimensions);
           var paths = new string[numberOfFrames];
            for (int intFrame = 0; intFrame < numberOfFrames; ++intFrame)
           {
               imageFile.SelectActiveFrame(frameDimensions, intFrame);
               var bmp = new Bitmap(imageFile);
               paths[intFrame] =   outputLocation + intFrame + ".jpg";
               bmp.Save(paths[intFrame], ImageFormat.Jpeg);
               bmp.Dispose();
           }
            imageFile.Dispose();
       }

   }

In this method we have simply calculated the no. of frames in tiff image and converted the active frame to Image

So now our complete code will be Something like this

using System.Drawing;
using System.Drawing.Imaging;

namespace TifftoImage
{
    class Program {
        static void Main(string[] args)
        {

            string inputTiffFileName = @"C:\Users\Ahmed\Desktop\MultipageTIFImage.tif";
            string outputLocation = @"C:\Users\Ahmed\Desktop\";
            TiffToImage(inputTiffFileName, outputLocation);

        }

        static void TiffToImage(string inputTiffFileName, string outputLocation)
        {
            var imageFile = Image.FromFile(inputTiffFileName);
            var frameDimensions = new FrameDimension(imageFile.FrameDimensionsList[0]);
            var numberOfFrames = imageFile.GetFrameCount(frameDimensions);
            var paths = new string[numberOfFrames];
             for (int intFrame = 0; intFrame < numberOfFrames; ++intFrame)
            {
                imageFile.SelectActiveFrame(frameDimensions, intFrame);
                var bmp = new Bitmap(imageFile);
                paths[intFrame] =   outputLocation + intFrame + ".jpg";
                bmp.Save(paths[intFrame], ImageFormat.Jpeg);
                bmp.Dispose();
            }
             imageFile.Dispose();
        }
    }
}

Just Debug the application and we will get our desired output.

I have attached the sample application and multipage tiff image.

Sample+TiffImage.rar (461.69 kb)

Posted by: Mohd Ahmed

Categories: C#, Console Application

Tags: , ,