JSON string to CSV and CSV to JSON conversion in c#

前端 未结 6 621
滥情空心
滥情空心 2020-11-28 08:01

I\'m working with JSON/CSV files in my asp.net web API project and tried with CSVHelper and ServiceStack.Text libraries but couldn\'t make it work.

The JSON file con

6条回答
  •  忘掉有多难
    2020-11-28 09:03

    public void Convert2Json() 
            { 
                try 
                { 
                    if (FileUpload1.PostedFile.FileName != string.Empty) 
                    { 
                        string[] FileExt = FileUpload1.FileName.Split('.'); 
                        string FileEx = FileExt[FileExt.Length - 1]; 
                        if (FileEx.ToLower() == "csv") 
                        { 
                            string SourcePath = Server.MapPath("Resources//" + FileUpload1.FileName); 
                            FileUpload1.SaveAs(SourcePath); 
                            string Destpath = (Server.MapPath("Resources//" + FileExt[0] + ".json")); 
    
                            StreamWriter sw = new StreamWriter(Destpath); 
                            var csv = new List(); 
                            var lines = System.IO.File.ReadAllLines(SourcePath); 
                            foreach (string line in lines) 
                                csv.Add(line.Split(',')); 
                            string json = new 
                                System.Web.Script.Serialization.JavaScriptSerializer().Serialize(csv); 
                            sw.Write(json); 
                            sw.Close(); 
                            TextBox1.Text = Destpath; 
                            MessageBox.Show("File is converted to json."); 
                        } 
                        else 
                        { 
                            MessageBox.Show("Invalid File"); 
                        } 
    
                    } 
                    else 
                    { 
                        MessageBox.Show("File Not Found."); 
                    } 
                } 
                catch (Exception ex) 
                { 
                    MessageBox.Show(ex.Message); 
                } 
            }
    

提交回复
热议问题