简体   繁体   English

从文件夹获取所有文件并使用C#和Json .net进行序列化时找不到文件异常

[英]File not found exception while get all files from a folder and serialize using C# and Json .net

I am trying to get all .json files from a folder dynamically to marge all .json files in a sigle .json file. 我正在尝试从文件夹中动态获取所有.json文件,以将所有.json文件置于单个.json文件中。 But while running the code I am getting file not found exception and could not run the program. 但是在运行代码时,我发现文件未发现异常,无法运行该程序。 My code to get all .json file is- 我获取所有.json文件的代码是-

 static void Main(string[] args)
    {
        var startPath = Application.StartupPath;
        var cities = new List<City>();
        DirectoryInfo d = new DirectoryInfo(startPath+@"\Flensburg\");
        foreach (var file in d.GetFiles())
        {
          using (StreamReader fi = File.OpenText(file.Name)) //getting file not found exception
          {
            JsonSerializer serializer = new JsonSerializer();
            City city = (City)serializer.Deserialize(fi, typeof(City));
            cities.Add(city);
         }
        }

        using (StreamWriter file = File.CreateText(@"C:\C# tutorial Backup\joint_josn\joint_josn\bin\Debug\cities.json"))
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(file, cities);
        }



    }

My json Object classes are- 我的json对象类是-

 public class GeoCoordinates
 {
  public double Longitude { get; set; }
  public double Latitude { get; set; }
 }

 public class Tourist
 {
  public string Name { get; set; }
  public string Shorttext { get; set; }
  public GeoCoordinates GeoCoordinates { get; set; }
  public List<string> Images { get; set; }
}

 public class City
 {
  public List<Tourist> Tourist { get; set; }
 }

 public class RootObject
 {
    public List<City> city { get; set; }
 }

My one json file look like this- 我的一个json文件看起来像这样-

   {
   "Name": "Flensburg Firth",
   "Shorttext": "Flensburg Firth or Flensborg Fjord  is the westernmost inlet of the Baltic Sea. It forms part of the border between Germany to the south and Denmark to the north. Its length is either 40 or 50 km, depending to the definition of its limits. It has the largest surface of all Förden and East Jutland Fjorde, which are a special type of inlets, different from geological fjords.\nTwo peninsulas, Broager peninsula on the northern side and Holnis peninsula on the southern side divide the inlet in an outer and an inner part. West of them, near the Danish coast, there are two small Islands called Okseøer.\nOn the Danish side, outer part of the northern limits of the firth is formed by the island of Als with the town of Sønderborg. Towards the west, continuing on the Danish side are Broager, Egernsund, Gråsten, Rinkenæs, Sønderhav, and Kollund.\nIn Germany at the Danish border there is Harrislee, at the inner end of the inlet the town of Flensburg, east of it on the southern shore the town of Glücksburg and the villages Munkbrarup, Langballig, Westerholz, Quern, Steinberg, Niesgrau, Gelting, and Nieby.\n\n",
  "GeoCoordinates": {
   "Longitude": 9.42901993,
    "Latitude": 54.7959404
   },
  "Images": [
  "CE3222F5.jpg"
   ]
  }

I have many more json files like the following files. 我还有许多其他的json文件,例如以下文件。

I want to serialize all the files in this way- 我想以这种方式序列化所有文件-

  {
   "Kiel": [ //city name
    {
       "Tourist": [
        {
            "Name": "Holstentor",
            "Shorttext": "The Holsten Gate is a city gate marking off the western boundary of the old center of the Hanseatic city of Lübeck. This Brick Gothic construction is one of the relics of Lübeck’s medieval city fortifications and one of two remaining city gates, the other being the Citadel Gate  Because its two round towers and arched entrance are so well known it is regarded today as a symbol of this German city, and together with the old city centre of Lübeck it has been a UNESCO World Heritage Site since 1987.\nHolstentor was built in 1464.",
            "GeoCoordinates": {
                "Longitude": 10.6797,
                "Latitude": 53.8662
            },
            "Images": [
                "https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Holstentor_in_L%C3%BCbeck_Frontseite_-_Zuschnitt.jpg/378px-Holstentor_in_L%C3%BCbeck_Frontseite_-_Zuschnitt.jpg"
            ]
        },
       {
            "Name": "Stadion Lohmühle",
            "Shorttext": "Das Stadion an der Lohmühle, oder auch einfach nur „Lohmühle“ genannt, ist ein reines Fußballstadion in Lübeck und das größte Stadion in Schleswig-Holstein.\nEs ist die Heimat des VfB Lübeck. Nach Abriss der alten Tribüne und dem Bau der neuen Haupttribüne in den 1990er Jahren im Zuge des Aufstiegs in die 2. Bundesliga im Jahre 1996 fasst das Stadion 17.869 Plätze, darunter etwa 4.400 überdachte Sitzplätze.\n\n",
            "GeoCoordinates": {
                "Longitude": 10.66888905,
                "Latitude": 53.88111115
            },
            "Images": [
                "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/L%C3%BCbeck-Lohm%C3%BChle_1.jpg/400px-L%C3%BCbeck-Lohm%C3%BChle_1.jpg"
            ]
        },

    //ans so on ..........

     ]

    }
  ]
 }

Documentation on File.CreateText indicates the path to be passed in is "The file to be opened for writing." File.CreateText上的文档指示要传递的路径是“要打开以进行写入的文件”。 but it appears you are passing it Application.StartupPath which would designate a folder rather than a file. 但似乎您正在传递给Application.StartupPath,它将指定一个文件夹而不是一个文件。 There are a few different spots in your code that a file not found could trigger. 您的代码中有一些不同的地方,找不到文件可能会触发。 If the above listed issue is not the source, try stepping through and letting us know exactly what line is throwing the error. 如果不是上面列出的问题,请尝试逐步解决问题,并让我们确切地知道哪一行引发了错误。

Edit 编辑

So since it appears your exception is being thrown on the first file access, I might try something like the following (something I grabbed from a project I'm currently working on) 因此,由于您的异常似乎是在首次访问文件时引发的,所以我可以尝试以下类似的操作(我从当前正在处理的项目中获取的内容)

dir = new DirectoryInfo(@"\\YourFilePath")
FileInfo[] files = dir.GetFiles("*.jpg");
            string filePath = "";
            StringCollection photos = new StringCollection();
            foreach (FileInfo file in files)
            {
                if (file.Name.ToLower().Contains(sku.ToLower()))
                {
                    filePath = path + file.Name;
                    photos.Add(filePath);
                }
            }

I can't help but think that using Directory.GetFiles() in the foreach loop may cause unexpected behavior. 我忍不住认为在foreach循环中使用Directory.GetFiles()可能会导致意外行为。 Also, you may want to break on the error, and figure out what filename the program is throwing the exception on. 另外,您可能想打破该错误,并弄清楚该程序在哪个文件名上引发异常。 Make sure the file is actually in the folder, has appropriate permissions, capitalization is the same etc etc. 确保文件实际上在文件夹中,具有适当的权限,大小写相同等。

So.. for your specific case: 所以..针对您的具体情况:

    DirectoryInfo d = new DirectoryInfo(startPath+@"\Flensburg\");
    FileInfo[] files = d.GetFiles("*.json");
    foreach (var file in files)
    {
      using (StreamReader fi = File.OpenText(file.Name)) //getting file not found exception
      {
        JsonSerializer serializer = new JsonSerializer();
        City city = (City)serializer.Deserialize(fi, typeof(City));
        cities.Add(city);
     }
    }

Replace file.Name with file.FullName; 用file.FullName替换file.Name;

var cities = new List(); var city = new List(); var myCities = new List { "Kiel", "Flensburg" }; var myCities = new List {“ Kiel”,“ Flensburg”};

        foreach (var c in myCities)
        {
            DirectoryInfo d = new DirectoryInfo(startPath + @"\" + c);
            var city = new City { Tourists = new List<Tourist>() };
            city.Name = c;
            foreach (var file in d.GetFiles())
            {
                using (StreamReader fi = File.OpenText(file.FullName)) //getting file not found exception
                {
                    JsonSerializer serializer = new JsonSerializer();
                    Tourist tourist = (Tourist)serializer.Deserialize(fi, typeof(Tourist));
                    city.Tourists.Add(tourist);
                }
            }

            cities.Add(city);
        }

        using (StreamWriter file = File.CreateText("output.json"))

Modified Code: 修改后的代码:

    static void Main(string[] args)
     {
        var startPath = Application.StartupPath;
        var city = new City { Tourist = new List<Tourist>() };
        DirectoryInfo d = new DirectoryInfo(startPath+@"\Flensburg\");
        foreach (var file in d.GetFiles())
        {
          using (StreamReader fi = File.OpenText(file.FullName))
          {
            JsonSerializer serializer = new JsonSerializer();
            Tourist tourist = (Tourist)serializer.Deserialize(fi, typeof(Tourist));
            city.Tourist.Add(tourist);
         }

        }

        using (StreamWriter file = File.CreateText(@"C:\C# tutorial Backup\joint_josn\joint_josn\bin\Debug\cities.json"))
        {
            JsonSerializer serializer = new JsonSerializer { Formatting = Formatting.Indented };
            serializer.Serialize(file, city);

        }



      }

The result I got is- 我得到的结果是-

   {
   "Tourist": [
      {
     "Name": "Flensburg Firth",
      "Shorttext": "Flensburg Firth or Flensborg Fjord  is the westernmost inlet of the Baltic Sea. It forms part of the border between Germany to the south and Denmark to the north. Its length is either 40 or 50 km, depending to the definition of its limits. It has the largest surface of all Förden and East Jutland Fjorde, which are a special type of inlets, different from geological fjords.\nTwo peninsulas, Broager peninsula on the northern side and Holnis peninsula on the southern side divide the inlet in an outer and an inner part. West of them, near the Danish coast, there are two small Islands called Okseøer.\nOn the Danish side, outer part of the northern limits of the firth is formed by the island of Als with the town of Sønderborg. Towards the west, continuing on the Danish side are Broager, Egernsund, Gråsten, Rinkenæs, Sønderhav, and Kollund.\nIn Germany at the Danish border there is Harrislee, at the inner end of the inlet the town of Flensburg, east of it on the southern shore the town of Glücksburg and the villages Munkbrarup, Langballig, Westerholz, Quern, Steinberg, Niesgrau, Gelting, and Nieby.\n\n",
      "GeoCoordinates": {
      "Longitude": 9.42901993,
      "Latitude": 54.7959404
     },
       "Images": [
       "CE3222F5.jpg"
     ]
   },
   {
    "Name": "Naval Academy Mürwik",
    "Shorttext": "The Naval Academy Mürwik is the main training establishment for all German Navy officers and replaced the German Imperial Naval Academy in Kiel.\nIt is located at Mürwik which is a part of Germany's most northern city, Flensburg. Built on a small hill directly by the coast, it overlooks the Flensburg Fjord. The main building of the academy is known for its beautiful architecture and location, and is often named the \"Red Castle\".\n\n",
     "GeoCoordinates": {
     "Longitude": 9.45944444,
     "Latitude": 54.815
    },
     "Images": [
     "34AADEDE.jpg"
    ]
   },
  {
     "Name": "Nordertor",
     "Shorttext": "The Nordertor is an old town gate in Flensburg, Germany, which was built around 1595. Today the landmark is used as a symbol for Flensburg.\n\n",
   "GeoCoordinates": {
    "Longitude": 9.43004861,
    "Latitude": 54.79541778
    },
   "Images": [
   "D02DCA3E.jpg"
   ]
  }
 ]
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从文件夹获取所有.json文件,然后使用C#和JSON.Net在单个.Json文件中进行序列化和序列化 - Get all .json Files from a Folder and then serialize in a single .Json File using C# and JSON.Net and Serialize 从特定文件夹获取Json文件并对其进行序列化 - Get a Json file from a specific folder and serialize it Json使用C#从文本文件序列化 - Json serialize from text file using c# 如何将Xml(从XLSX文件)序列化为Json? C#.NET Json.Net - How to serialize Xml (from XLSX files) to Json ? C# .NET Json.Net 使用 C# 从 Azure DataLake 获取所有文件夹中所有文件的列表 - Get List of all files from all folder from Azure DataLake using C# c#如何获取文件夹中的所有文件,无论其文件类型如何 - c# How to get all files in a folder regardless of their file type 如何使用 c# 从 UWP 中的文件夹“C:\\Test”中获取所有文本文件? - How to get all text files from a folder "C:\Test" in UWP using c#? 使用JSON.Net从JSON序列化为XML的问题-C# - Issues Using JSON.Net to serialize from JSON to XML - C# 如何在c#中将自定义异常序列化为json - How to serialize a custom exception to json in c# 我如何使用JSON.net从c#中的JSON文件中获取密钥及其对象? - How do I get the key and it's object from a JSON file in c# using JSON.net?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM