簡體   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