0

variablepathが空で、editor.Text空でない場合、SaveFileDialog が表示されます。

さて、一体なぜこのいまいましいことは失敗しているのですか?

私は同じ結果でコードの多くの異なるバリエーションでこれを試しました:FAIL:

if(path.Length >= 1) // path contains a path. Save changes instead of creating NEW file.
{
   File.WriteAllText(path, content);
}
else
{
   // no path defined. Create new file and write to it.
   using(SaveFileDialog saver = new SaveFileDialog())
   {
      if(saver.ShowDialog() == DialogButtons.OK)
      {
         File.WriteAllText(saver.Filename, content);
      }
   }
}

私が持っているコードファイルの上部に:

パス = String.Empty;

では、以下のバリエーションをすべて試した後でも、毎回これが失敗するのはなぜですか?

if(path.Length > 1) // path contains a path. Save changes instead of creating NEW file.
{
   File.WriteAllText(path, content);
}
else
{
   // no path defined. Create new file and write to it.
   using(SaveFileDialog saver = new SaveFileDialog())
   {
      if(saver.ShowDialog() == DialogButtons.OK)
      {
         File.WriteAllText(saver.Filename, content);
      }
   }
}

if(String.IsNullOrEmpty(path)) // path contains a path. Save changes instead of creating NEW file.
{
   File.WriteAllText(path, content);
}
else
{
   // no path defined. Create new file and write to it.
   using(SaveFileDialog saver = new SaveFileDialog())
   {
      if(saver.ShowDialog() == DialogButtons.OK)
      {
         File.WriteAllText(saver.Filename, content);
      }
   }
}

if(String.IsNullOrWhiteSpace(path)) // path contains a path. Save changes instead of creating NEW file.
{
   File.WriteAllText(path, content);
}
else
{
   // no path defined. Create new file and write to it.
   using(SaveFileDialog saver = new SaveFileDialog())
   {
      if(saver.ShowDialog() == DialogButtons.OK)
      {
         File.WriteAllText(saver.Filename, content);
      }
   }
}

これは私をとても怒らせています。これはどのように失敗する可能性がありますか?

pathブレークポイントを設定すると、それが間違いなく null/であることがわかり""ます。

4

4 に答える 4

5

あなたが書いた理由:

if(saver.ShowDialog() == DialogButtons.OK)

それ以外の:

if(saver.ShowDialog() == DialogResult.OK)
于 2013-07-03T16:59:52.803 に答える
1

パスは文字列で、ファイルへのフルパスですか? いっぱいになった場合、ファイルが実際に存在することを意味するわけではありません。そのようにすることをお勧めします。

if(System.IO.File.Exists(path))
{

}
else
{

}

File.Exists(null) は false を返すので、これで問題なく動作します

あなたのやり方を使いたいなら、最後の2つのステートメントに「!」が欠けているだけだと思います。

if (!String.IsNullOrWhiteSpace(path)) 

if(!String.IsNullOrEmpty(path))

length プロパティにアクセスする前に null かどうかを確認します

if(path != null && path.Length > 1) 
于 2013-07-03T17:00:41.313 に答える
0

これを試して:

 if (string.IsNullOrWhiteSpace(path) && !string.IsNullOrWhiteSpace(editor.Text))
 {
       // no path defined. Create new file and write to it.
       using (SaveFileDialog saver = new SaveFileDialog())
       {
            if (saver.ShowDialog() == DialogResult.OK)
            {
                 File.WriteAllText(saver.Filename, content);
            }
       }                
  }
  else if(File.Exists(path)
  {
       File.WriteAllText(path, content);
  }
于 2013-07-03T17:15:39.417 に答える