C#DateTime变量读取csv文件(如果为空)如何返回字符串消息

时间:2019-06-09 03:29:34

标签: c# datetime

我是C#初学者,想问一个问题。

如果从csv文件读取的数据为空,如何返回DateTime变量的字符串消息“从不”?

这是我的代码:

class GroceryItem
{
    public string Description { get; private set; }
    public decimal Price { get; set; }
    public DateTime ExpirationDate { get; private set; }

    public GroceryItem()
    { }

    public GroceryItem(string descr, decimal p, DateTime date)
    {
        Description = descr;
        Price = p;
        ExpirationDate = date;
    }
}

class GroceryItemCollection : List<GroceryItem>

class ConsolePrinter
{
    public static void PrintHeader()
    {
        Console.WriteLine("{0, -20} {1, 8} {2, -28}", "Grocery Item", "Price", "Expires");
        Console.WriteLine(new string('-', 47));
    }

    public static void PrintCollection(GroceryItemCollection items)
    {
        foreach(GroceryItem item in items)
        {
            Console.WriteLine("{0, -20} {1, 8} {2, -28}", 
                item.Description, item.Price, item.ExpirationDate.ToString("ddd MMM d, yyyy"));                               
        }

        Console.WriteLine(new string('-', 47));
        Console.WriteLine("{0, -20} {1, 8}", "Total", items.TotalPrice);
    }
}

class Program
{
    static void Main(string[] args)  
    {
        string path;           

        if(args.Length > 0)
        {
            path = args[0];
        }
        else
        {
            Console.WriteLine("No file found");
            return;
        }

        StreamReader sr = null;
        string lineData;
        GroceryItemCollection items = new GroceryItemCollection(); 

        if (File.Exists(path))
        {
            try
            {
                using(sr = new StreamReader(path))
                {
                    while(sr.Peek() > 0)
                    {
                        lineData = sr.ReadLine();
                        string[] lineElement = lineData.Split(',');                            

                        string description;
                        decimal price;
                        DateTime expirationDate;
                        description = lineElement[0];
                        bool priceSuccess = decimal.TryParse(lineElement[1], out price);

                        bool expirationDateSuccess = DateTime.TryParse(lineElement[2], out expirationDate);
                        items.Add(new GroceryItem(description, price, expirationDate));
                    }                        

                    ConsolePrinter.PrintHeader();
                    ConsolePrinter.PrintCollection(items);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"\n{ex.Message}\n");
            }
        }
    }
} 

从csv数据中预期返回的“杂货项目”,“价格”,“过期”

如果csv数据为空,如何在上面修复我的代码并返回Expires数据的字符串消息“从不”?

我的代码返回默认日期“ 0001年1月1日星期一”

谢谢

0 个答案:

没有答案