如何将文本限定符合并到用作变量的文件名中?

时间:2015-05-12 17:18:10

标签: c# csv ssis

我有一个C#脚本,它接收两个CSV文件作为输入,组合这两个文件,对它们执行大量计算,并将结果写入新的CSV文件。 这两个输入CSV文件名称声明为变量,并通过访问这些变量名称在C#脚本中使用。

输入CSV文件中的数据如下所示: enter image description here

由于数据的值为数千和数百万,因此C#代码中的行拆分会错误地截断数据。例如,值11,861仅出现在11和681在下一列中。

在C#中是否有任何方法可以为这两个文件指定文本限定符(在本例中为#34;)

以下是C#代码段:

 string[,] filesToProcess = new string[2, 2] { {(String)Dts.Variables["csvFileNameUSD"].Value,"USD" }, {(String)Dts.Variables["csvFileNameCAD"].Value,"CAD" } };
string headline = "CustType,CategoryType,CategoryValue,DataType,Stock QTY,Stock Value,Floor QTY,Floor Value,Order Count,Currency";
string outPutFile = Dts.Variables["outputFile"].Value.ToString();
//Declare Output files to write to
FileStream sw = new System.IO.FileStream(outPutFile, System.IO.FileMode.Create);
StreamWriter w = new StreamWriter(sw);
w.WriteLine(headline);

//Loop Through the files one by one and write to output Files
for (int x = 0; x < filesToProcess.GetLength(1); x++)
{                
    if (System.IO.File.Exists(filesToProcess[x, 0]))
    {
        string categoryType = "";
        string custType = "";
        string dataType = "";
        string categoryValue = "";

        //Read the input file in memory and close after done
        StreamReader sr = new StreamReader(filesToProcess[x, 0]);
        string fileText = sr.ReadToEnd();
        string[] lines = fileText.Split(Convert.ToString(System.Environment.NewLine).ToCharArray());
        sr.Close();                   

其中csvFileNameUSD和csvFileNameCAD是具有指向其位置的值的变量。

2 个答案:

答案 0 :(得分:2)

嗯,基于你回答的问题,这应该做你想做的事情:

public void SomeMethodInYourCodeSnippet()
{
    string[] lines;
    using (StreamReader sr = new StreamReader(filesToProcess[x, 0]))
    {
        //Read the input file in memory and close after done
        string fileText = sr.ReadToEnd();
        lines = fileText.Split(Convert.ToString(System.Environment.NewLine).ToCharArray());
        sr.Close();  // redundant due to using, but just to be safe...
    }

    foreach (var line in lines)
    {
        string[] columnValues = GetColumnValuesFromLine(line);
        // Do whatever with your column values here...
    }
}
private string[] GetColumnValuesFromLine(string line)
{
    // Split on ","
    var values = line.Split(new string [] {"\",\""}, StringSplitOptions.None);
    if (values.Count() > 0)
    {
        // Trim leading double quote from first value
        var firstValue = values[0];
        if (firstValue.Length > 0)
            values[0] = firstValue.Substring(1);

        // Trim the trailing double quote from the last value
        var lastValue = values[values.Length - 1];
        if (lastValue.Length > 0)
            values[values.Length - 1] = lastValue.Substring(0, lastValue.Length - 1);
    }
    return values;
}

尝试一下,让我知道它是如何工作的!

答案 1 :(得分:0)

几天前你发布了一个非常相似的question。这个解决方案对你有帮助吗?

如果是这样,你面临的问题是什么。我们也可以帮助您排除故障。

相关问题