C# pass file text to list when file is entered via

2019-08-24 18:00发布

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 |

2条回答
Root(大扎)
2楼-- · 2019-08-24 18:46

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}");
        }
    }

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

1) Validate command line inputs before using.

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

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!

查看更多
在下西门庆
3楼-- · 2019-08-24 18:47

If you want to convert Array to List, you can just call Add or Insert to make it happen.

According to your code, you can do Inventory.Add(Item).

while ((line = f1.ReadLine()) != null)
{
    string[] currentLine = line.Split('|');
    Item = new InventoryItem {
        Index = Convert.ToInt16(currentLine[0]),
        Value = Convert.ToDouble(currentLine[1])
    };
    Inventory.Add(Item);
}

like this.

查看更多
登录 后发表回答