简体   繁体   中英

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. 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-

 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-

 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-

   {
   "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.

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." but it appears you are passing it Application.StartupPath which would designate a folder rather than a file. 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. 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;

var cities = new List(); 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"
   ]
  }
 ]
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM