using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.IO;
using System.Windows.Forms;
public class SaveHelper
{
public static bool IsValidFileName(string fileName)
{
System.Diagnostics.Debug.Assert(fileName != null);
bool isValid = true;
try
{
FileInfo fileInfor = new FileInfo(fileName);
if (fileInfor.Name != fileName)
{
isValid = false;
}
}
catch (ArgumentException ex)
{
isValid = false;
}
catch (PathTooLongException ex)
{
isValid = false;
}
catch (NotSupportedException ex)
{
isValid = false;
}
catch (Exception e)
{
//isValid = true;
}
return isValid;
}
public static bool IsReadOnly(string fileName)
{
bool isReadonly = false;
try
{
FileInfo fileInfor = new FileInfo(fileName);
if (fileInfor.Exists)
{
isReadonly = fileInfor.IsReadOnly;
}
else
{
System.Diagnostics.Debug.Fail("File is not exist.");
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Fail(ex.Message);
}
return isReadonly;
}
private static string AddExtension(string filename, string ext,bool replace)
{
int ind = filename.LastIndexOf(".");
if (ind < 0)
{
return filename + "." + ext;
}
else if (filename.Substring(ind + 1).ToLower() != ext.ToLower())
{
if (replace)
return filename.Substring(0, ind) + "." + ext;
else
return filename + "." + ext;
}
else
{
return filename;
}
}
public static void SavingWidgetDialog(string Name, string uid)
{
if ((Name == null) || (Name.Trim().Length == 0)
|| (uid == null) || uid.Trim().Length == 0)
return;
Stream stream = null;
SaveFileDialog dialog = new SaveFileDialog();
dialog.AddExtension = true;
dialog.DefaultExt = "bidml";
string filter = string.Format("(*.x)|*.x|{2} (*.*)|*.*");
dialog.Filter = filter;
dialog.FilterIndex = 1;
dialog.RestoreDirectory = true;
dialog.OverwritePrompt = false;
dialog.Title = "保存";
string tempfilename =AddExtension(Name, dialog.DefaultExt,true);
if (WidgetSaveHelper.IsValidFileName(tempfilename))
{
dialog.FileName = tempfilename;
}
dialog.FileOk += new CancelEventHandler(dialog_FileOk);
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((stream = dialog.OpenFile()) != null)
{
using (stream)
{
stream.Close();
}
}
}
catch (Exception ex)
{
if (stream != null)
stream.Close();
string errorMessage = "lala";
string caption = "lalala";
try
{
File.Delete(dialog.FileName);
}
catch (Exception e)
{
}
}
}
}
private static void dialog_FileOk(object sender, CancelEventArgs e)
{
SaveFileDialog dialog = sender as SaveFileDialog;
dialog.FileName = AddExtension(dialog.FileName, dialog.DefaultExt, false);
if (File.Exists(dialog.FileName))
{
string overwriteMessage = "lala";
string readonlyMessage = "lalala";
string caption = "la";
//window.Form.StartPosition = FormStartPosition.CenterScreen;
if (SaveHelper.IsReadOnly(dialog.FileName))
{
e.Cancel = true;
}
else
{
//DialogResult dr = window.Form.ShowDialog();
if (dr != DialogResult.OK)
{
e.Cancel = true;
}
}
}
}
}