【问题标题】:File not found exception while get all files from a folder and serialize using C# and Json .net从文件夹中获取所有文件并使用 C# 和 Json .net 序列化时找不到文件异常
【发布时间】:2016-02-16 15:15:04
【问题描述】:

我正在尝试动态地从文件夹中获取所有 .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 ..........

     ]

    }
  ]
 }

【问题讨论】:

  • 我假设这只是一个错字,您并没有真正尝试在没有文件名的情况下直接写入启动路径。
  • @kjbartel:请您解释一下。在放置断点时,我只得到名字。但之后它显示文件未找到并且无法在其中获取任何值
  • 这是一个用调试器发现这个错误的好机会。作为专业人士,您需要能够相当系统地发现这些简单的错误。

标签: c# json serialization exception-handling deserialization


【解决方案1】:

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

【讨论】:

  • @Nata 是的。在我的调试文件夹中有名为 Flensburg 的文件夹,在 flensburg 文件夹中我有 Flensburg Firth.json、Naval Academy Mürwik.json 和许多文件。但是我应该为此修改什么
【解决方案2】:

用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"))

【讨论】:

  • 替换。但是我以这种方式得到了我的输出 [{"Tourist":null},{"Tourist":null},{"Tourist":null}]
  • file.Name 只是文件名; File.OpenText 将搜索 Application.StartupPath 文件夹中的文件。
  • 好的。但我无法进入文件的内容
  • json文件不正确;它应该是 {Tourist:[{ "Name":...},{Name:...}]}
  • 你所拥有的是旅游对象,而不是城市对象
【解决方案3】:

修改代码:

    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"
   ]
  }
 ]
 }

【讨论】:

    猜你喜欢
    • 2016-05-27
    • 2022-01-07
    • 1970-01-01
    • 2015-09-30
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多