1

C# Windows アプリケーションから .xml ファイルを読み込もうとしている .net Windows アプリケーションが 1 つあります。

しかし、私はエラーが発生しています:

パス 'c:\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\~\Files\test.xml' の一部が見つかりませんでした。

しかし、私のファイルは、アプリケーションではなく アプリケーション内にFilesあるフォルダにありますWindowsFormsApplication1\bin\Debug

では、なぜそれが検索されているの\bin\Debugですか?

form.cs のコード

DataSet dsAuthors = new DataSet("authors");
            string filePath = @"~/Files/test.xml";

            dsAuthors.ReadXml(filePath);

また、Web アプリケーションで行うように Server.MapPath を使用する方法があることを教えてください。

私は次のような他の解決策を試しました:

string appPath = Path.GetDirectoryName(Application.ExecutablePath);

            System.IO.DirectoryInfo directoryInfo = System.IO.Directory.GetParent(appPath);
            System.IO.DirectoryInfo directoryInfo2 = System.IO.Directory.GetParent(directoryInfo.FullName);

            string path = directoryInfo2.FullName + @"\Files";

しかし、エラーが発生しています: Access to the path is denied.

4

2 に答える 2

2

試す:

        string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine("Files", "test.xml"));// @"~/Files/test.xml";

うまくいかない場合は、test.xml の「出力ディレクトリにコピー」プロパティが「常にコピー」に設定されていることを確認してください。

于 2012-06-26T06:48:51.763 に答える
0

使用するServer.MapPath

相対URLを使用しています。これはReadXmlでは機能しません。ディスク上の絶対パスが必要です。

Server.MapPathは仮想パスを取得し、その絶対パスを提供します。

var fullPath = Server.MapPath("~/Files/test.xml");
dsAuthors.ReadXml(fullPath);

注:Server.MapPathは、パスが実際に存在するかどうかを確認しません。

于 2012-06-26T06:43:48.230 に答える