如果变量path为空,而editor.Text为空,则应显示SaveFileDialog。
为什么这该死的东西会失败?
我尝试了许多不同的代码变体,结果都是一样的:失败:
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);
}
}
}在代码文件的顶部,我有:
path = 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/""。
发布于 2013-07-03 16:59:52
你为什么写:
if(saver.ShowDialog() == DialogButtons.OK)而不是:
if(saver.ShowDialog() == DialogResult.OK)发布于 2013-07-03 17:12:15
如果path是null,那么在尝试获取path.Length时将得到一个异常。若要检查空路径,请使用String.IsNullOrWhiteSpace(path)版本。您还需要一个条件来检查您的第二个需求。
if(!String.IsNullOrWhiteSpace(path)) // path contains a path. Save changes instead of creating NEW file.
{
File.WriteAllText(path, content);
}
else if (!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);
}
}
}发布于 2013-07-03 17:00:41
路径是一个字符串,它是文件的完整路径吗?如果文件已被填充,但这并不意味着该文件确实存在,您最好这样做:
if(System.IO.File.Exists(path))
{
}
else
{
}File.Exists(null)返回false,因此这将很好地工作。
如果你想用你的方式,那么我想你的最后两句话只是少了一个"!“
if (!String.IsNullOrWhiteSpace(path))
if(!String.IsNullOrEmpty(path))在访问length属性之前检查是否为null
if(path != null && path.Length > 1) https://stackoverflow.com/questions/17453767
复制相似问题