我正在Windows 7中创建一个appliaction。我使用SaveFileDialog让用户选择保存文件的位置。
在Windows 7中,如果你选择一个只读文件并尝试覆盖,你会得到一个弹出窗口,说你不能。然后,您必须选择另一个文件来覆盖或只创建一个新的保存。
我遇到的问题是,在Windows XP中你没有得到弹出消息说你不能保存。相反,该程序会抛出异常。
************** Exception Text **************
System.UnauthorizedAccessException: Access to the path 'C:\spanish.xml' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.Xml.XmlWriterSettings.CreateWriter(String outputFileName)
at System.Xml.XmlWriter.Create(String outputFileName, XmlWriterSettings settings)
at TOOL.XMLExporter.export(TabControl& languageTabs, ProgressBar& progressBar1, Int32 selectedLanguage)
at TOOL.Main.exportToXML()
at TOOL.Main.toxmlToolStripMenuItem_Click(Object sender, EventArgs e)
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
这是我调用的代码:
SaveFileDialog fldg = new SaveFileDialog();
fldg.Title = "Save File";
fldg.InitialDirectory = @"c:\";
fldg.Filter = "(*.xml)|*.xml";
fldg.FilterIndex = 2;
fldg.RestoreDirectory = true;
string path = "";
if (fldg.ShowDialog() == DialogResult.OK)
{
path = fldg.FileName;
}
有没有办法检查文件是否只读,如果是,则显示相同的消息(在xp中)。
答案 0 :(得分:4)
再次调用SaveFileDialog:
bool foundFile = false;
SaveFileDialog dlg = new SaveFileDialog();
while (!foundFile)
{
if (dlg.ShowDialog() != DialogResult.OK)
break;
FileInfo info = new FileInfo(dlg.FileName);
if (!info.IsReadOnly)
{
MessageBox.Show("File is readonly.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
foundFile = true;
}
}
文件是只读的吗?
FileInfo info = new FileInfo(filename);
if(info.IsReadOnly)
{
...
}