通过命令行参数输入文件时,C#将文件文本传递给列表 [英] C# pass file text to list when file is entered via command line argument

查看:40
本文介绍了通过命令行参数输入文件时,C#将文件文本传递给列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,用于读取两个文本文件并将其数据写入第三个文本文件.我被指示将一个文件的内容传递到列表中.我做过类似的事情,将内容传递给数组(见下文).但我似乎无法使其与列表配合使用.

I am writing a program for an assignment that is meant to read two text files and use their data to write to a third text file. I was instructed to pass the contents of the one file to a list. I have done something similar, passing the contents to an array (see below). But I can't seem to get it to work with a list.

这是我过去使用数组所做的事情:

Here is what I have done in the past with arrays:

 StreamReader f1 = new StreamReader(args[0]);
        StreamReader f2 = new StreamReader(args[1]);
        StreamWriter p = new StreamWriter(args[2]);
        double[] array1 = new double[20];
        double[] array2 = new double[20];
        double[] array3 = new double[20];

        string line;
        int index;
        double value;

 while ((line = f1.ReadLine()) != null)
        {
            string[] currentLine = line.Split('|'); 
            index = Convert.ToInt16(currentLine[0]);
            value = Convert.ToDouble(currentLine[1]);
            array1[index] = value;
        }

如果有兴趣,这是我当前的设置:

If it is of any interest, this is my current setup:

 static void Main(String[] args)
    {
        // Create variables to hold the 3 elements of each item that you will read from the file
        // Create variables for all 3 files (2 for READ, 1 for WRITE)
        int ID;
        string InvName;
        int Number;

        string IDString; 
        string NumberString;

        string line; 

        List<InventoryNode> Inventory = new List<InventoryNode>();
        InventoryNode Item = null;

        StreamReader f1 = new StreamReader(args[0]);
        StreamReader f2 = new StreamReader(args[1]);
        StreamWriter p = new StreamWriter(args[2]);


        // Read each item from the Update File and process the data

        //Data is separated by pipe |

推荐答案

如果我理解正确,那么您要做的就是读取两个输入文件,以特定格式解析这些文件中的数据(在这种情况下为int | double ),然后将其写入新文件.如果这是必需的,请尝试以下代码,因为不确定您希望数据如何显示在第三个文件中,我保持了原来的格式(即int | double)

If I understand it correctly all you want to do is read two input file, parse the data in these file in a particular format (in this case int|double) and then write it to a new file. If this is the requirement, please try out the following code, as it is not sure how you want the data to be presented in the third file I have kept the format as it is (i.e. int|double)

 static void Main(string[] args)
    {

        if (args == null || args.Length < 3)
        {
            Console.WriteLine("Wrong Input");
            return;
        }

        if (!ValidateFilePath(args[0]) || !ValidateFilePath(args[1]))
        {
            return;
        }

        Dictionary<int, double> parsedFileData = new Dictionary<int, double>();

        //Read the first file
        ReadFileData(args[0], parsedFileData);

        //Read second file 
        ReadFileData(args[1], parsedFileData);

        //Write to third file
        WriteFileData(args[2], parsedFileData);
    }

    private static bool ValidateFilePath(string filePath)
    {
        try
        {
            return File.Exists(filePath);
        }
        catch (Exception)
        {
            Console.WriteLine($"Failed to read file : {filePath}");
            return false;
        }
    }

    private static void ReadFileData(string filePath, Dictionary<int, double> parsedFileData)
    {
        try
        {
            using (StreamReader fileStream = new StreamReader(filePath))
            {
                string line;
                while ((line = fileStream.ReadLine()) != null)
                {
                    string[] currentLine = line.Split('|');
                    int index = Convert.ToInt16(currentLine[0]);
                    double value = Convert.ToDouble(currentLine[1]);

                    parsedFileData.Add(index, value);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception : {ex.Message}");
        }
    }

    private static void WriteFileData(string filePath, Dictionary<int, double> parsedFileData)
    {
        try
        {
            using (StreamWriter fileStream = new StreamWriter(filePath))
            {
                foreach (var parsedLine in parsedFileData)
                {
                    var line = parsedLine.Key + "|" + parsedLine.Value;
                    fileStream.WriteLine(line);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception : {ex.Message}");
        }
    }

在编写C#代码时,您应该牢记以下几点:

There are few things you should always remember while writing a C# code :

1)在使用前验证命令行输入.

1) Validate command line inputs before using.

2)始终查找具有dispose方法的任何类,并使用block在内部将其实例化.

2) Always lookout for any class that has dispose method, instantiate it inside using block.

3)代码中有适当的机制来捕获异常,否则您的程序将在运行时因无效输入或无法验证的输入而崩溃!

3) Proper mechanism in the code to catch exceptions, else your program would crash at runtime with invalid inputs or inputs that you could not validate!

这篇关于通过命令行参数输入文件时,C#将文件文本传递给列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆