繁体   English   中英

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

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

我正在尝试从文件夹中动态获取所有.json文件,以将所有.json文件置于单个.json文件中。 但是在运行代码时,我发现文件未发现异常,无法运行该程序。 我获取所有.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);
        }



    }

我的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; }
 }

我的一个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"
   ]
  }

我还有许多其他的json文件,例如以下文件。

我想以这种方式序列化所有文件-

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

     ]

    }
  ]
 }

File.CreateText上的文档指示要传递的路径是“要打开以进行写入的文件”。 但似乎您正在传递给Application.StartupPath,它将指定一个文件夹而不是一个文件。 您的代码中有一些不同的地方,找不到文件可能会触发。 如果不是上面列出的问题,请尝试逐步解决问题,并让我们确切地知道哪一行引发了错误。

编辑

因此,由于您的异常似乎是在首次访问文件时引发的,所以我可以尝试以下类似的操作(我从当前正在处理的项目中获取的内容)

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

我忍不住认为在foreach循环中使用Directory.GetFiles()可能会导致意外行为。 另外,您可能想打破该错误,并弄清楚该程序在哪个文件名上引发异常。 确保文件实际上在文件夹中,具有适当的权限,大小写相同等。

所以..针对您的具体情况:

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

用file.FullName替换file.Name;

var city = 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"))

修改后的代码:

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

        }



      }

我得到的结果是-

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

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