Solved

Convert / transform csv into txt file using .net / C#

Posted on 2010-08-15
8
2,838 Views
Last Modified: 2013-12-17
Hi All

I wish to do the following:

Loop via parent folder through all sub folders, and convert each csv file into a txt.

There are many csv to xml or txt to xml solutions, etc but I had trouble finding a solution for this.

I was thinking to convert to xml, but it is best for me to convert to txt format as it suits my needs.

thanks in advance for your help
0
Comment
Question by:dataviss
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 30

Expert Comment

by:IanTh
ID: 33439782
easy

do an array for the input and read the csv file in and then when finished input write out the array to a txt file
for instance  

public infile as new streamreader     'for the input
public outfile as new streamwriter    ' for output
dim input_array (x,y) as array
dim inputfile as string

If File.Exists(inputfile) Then
            Dim reader As New StreamReader(inputfile, True)
            Dim s As String = reader.ReadLine()
            reader.Close()
            If Not (s Is Nothing) AndAlso s.Length > 0 Then
                'nothing in file
            Else
                'code to write array
            End If
        Else
            Dim f As FileStream = File.Create(infile)
            f.Close()
            end If


to write it something like
for a= 1++ to arraymax
filename = String.Format("c:\ians\{0:g}log.csv", DateTime.Now.Day & DateTime.Now.Month & DateTime.Now.Year)
            outfile = New StreamWriter(filename, False)
           
0
 

Author Comment

by:dataviss
ID: 33439811
Hi thanks for the response

I wanted to use the same fileName as per original .csv files, and it seems that this method does not loop through the parent and checks for sub folders if they exist, and process those too.

thanks
0
 
LVL 47

Expert Comment

by:Wayne Taylor (webtubbs)
ID: 33440083
Umm, a CSV file *is* a text file. It's just a flat text file with Comma Seperated Values (hence the name).

So, seeing as it's already a text file, if you want to change the extension to "txt", use the My.Computer.FileSystem.RenameFile method...

http://msdn.microsoft.com/en-us/library/2ce15by3.aspx

Wayne
0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 

Author Comment

by:dataviss
ID: 33440149
Apologies I will explain myself better...

I am looking to change the format from csv to tab delimited separate values (tsv) of each csv file in the current and sub folder paths

thanks
0
 
LVL 30

Expert Comment

by:IanTh
ID: 33440734
yes you will need to strip out the commas and thats why you need an array as yyou can read it in as a csv into the array and then write it to a text file straight from the array
0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 33441120
Here's the basic algorithm...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string pattern = "*.csv";
            string RootFolder = @"c:\some\path\root\folder";
            RecurseFolders(new DirectoryInfo(RootFolder), pattern);
        }

        private void RecurseFolders(DirectoryInfo di, string pattern)
        {
            foreach (FileInfo fi in di.GetFiles(pattern))
            {
                ConvertCSVtoTabDelimited(fi);
            }
            foreach (DirectoryInfo subDi in di.GetDirectories())
            {
                RecurseFolders(subDi, pattern);
            }
        }

        private void ConvertCSVtoTabDelimited(FileInfo fi)
        {
            try
            {
                System.IO.File.WriteAllText(fi.FullName, System.IO.File.ReadAllText(fi.FullName).Replace(",", "\t"));
            }
            catch (Exception ex)
            {
                MessageBox.Show("File: " + fi.FullName + Environment.NewLine + Environment.NewLine + ex.ToString(), "Error Converting File", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }
}

Open in new window

0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 33441140
*If you want to create a new file in the same location, but with a .tsv extension instead of .csv, then change the ConvertCSVtoTabDelimited() method to:
        private void ConvertCSVtoTabDelimited(FileInfo fi)
        {
            try
            {
                string NewFileName = Path.Combine(Path.GetDirectoryName(fi.FullName),   Path.GetFileNameWithoutExtension(fi.FullName) + ".tsv");
                System.IO.File.WriteAllText(NewFileName, System.IO.File.ReadAllText(fi.FullName).Replace(",", "\t"));
            }
            catch (Exception ex)
            {
                MessageBox.Show("File: " + fi.FullName + Environment.NewLine + Environment.NewLine + ex.ToString(), "Error Converting File", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

Open in new window

0
 

Author Closing Comment

by:dataviss
ID: 33441179
thanks for that as i addressed all my requirements
0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

689 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question