YoungStamos YoungStamos - 3 months ago 9
C# Question

Quote-Enclosing 600+ CSV files in a directory c#

I currently have this method that can successfully quote-enclose a single CSV file but I am trying to loop through 600+ CSV files in a directory and perform the Quote Enclose method on each one. I am unsure how to do this effectively. Any feedback is appreciated.

Below is my code:

public void QuoteEnclosingCSV()
{
string fileNamePath = Path.GetTempPath() + @"\Reports\*.csv";

var stringBuilder = new StringBuilder();

foreach (var line in File.ReadAllLines(fileNamePath))
{
stringBuilder.AppendLine(string.Format("\"{0}\"", string.Join("\",\"", line.Split(','))));
}

File.WriteAllText(string.Format(fileNamePath, Path.GetDirectoryName(fileNamePath)), stringBuilder.ToString());

}

string marFolder = Path.GetTempPath() + @"\Reports\";

var dir = new DirectoryInfo(marFolder);

foreach (var file in dir.EnumerateFiles("*.csv"))
{
QuoteEnclosingCSV();
}


Below is the error I'm receiving:


Illegal characters in path.

Answer

My first step in unraveling this conundrum would be to guess what the error message is trying to tell me. My first guess would be that it's trying to say that the path has illegal characters in it. Did you stop to check what characters were in the path that you get the error on?

I'll show you:

C:\Users\YoungStamos\AppData\Local\Temp\\Reports\*.csv

That's the path you pass to File.ReadAllLines(). The single argument to that method is a path to one single file. You can't have an asterisk (*) in a filename in Windows, because it's a wildcard.

What you seem to be trying to do is pass a parameter to QuoteEnclosingCSV(). In this loop, you carefully list each file, but you never tell QuoteEnclosingCSV() about any of them.

foreach (var file in dir.EnumerateFiles("*.csv"))
{
    QuoteEnclosingCSV();
}

This is more like what you want:

public void QuoteEnclosingCSV(string fileNamePath)
{
    var stringBuilder = new StringBuilder();

    foreach (var line in File.ReadAllLines(fileNamePath))
    {
        stringBuilder.AppendLine(string.Format("\"{0}\"", string.Join("\",\"", line.Split(','))));
    }

    //  I don't know what string.Format() is meant to do here; I'm guessing your guess is 
    //  as good as mine, so I'm eliminating it. 
    //File.WriteAllText(string.Format(fileNamePath, Path.GetDirectoryName(fileNamePath)), stringBuilder.ToString());

    File.WriteAllText(fileNamePath, stringBuilder.ToString());
}

And then call it like this:

string marFolder = Path.Combine(Path.GetTempPath(), "Reports");

var dir = new DirectoryInfo(marFolder);

foreach (var fileInfo in dir.EnumerateFiles("*.csv"))
{
    QuoteEnclosingCSV( fileInfo.FullName );
}
Comments