private bool SaveToFile(string sText,string sFileName) { try { System.IO.StreamWriter sw = System.IO.File.CreateText(sFileName); sw.WriteLine(sText); return true; } catch { return false; } } private void button2_Click(object sender, EventArgs e) { string Dir = @"D:AdministratorDesktop"; string FileTitle = "新建 文本文档"; string FileExt = ".txt"; string s1 = Dir + FileTitle + FileExt; int j = 2; if (System.IO.File.Exists(s1)) { string s = string.Format("{0}{1}({2}){3}", Dir, FileTitle, j, FileExt); while (System.IO.File.Exists(s)) { j++; s = string.Format("{0}{1}({2}){3}", Dir, FileTitle, j, FileExt); } if (!System.IO.File.Exists(s)) SaveToFile(textBox1.Text, s); } else SaveToFile(textBox1.Text, s1); }
private bool SaveToFile(string sText,string sFileName) { try { System.IO.StreamWriter sw = System.IO.File.CreateText(sFileName); sw.WriteLine(sText); return true; } catch { return false; } } private string CreateFile2(string sText, string sFileName) { string Dir = System.IO.Path.GetDirectoryName(sFileName)+"\"; string FileTitle = System.IO.Path.GetFileNameWithoutExtension(sFileName); string FileExt = System.IO.Path.GetExtension(sFileName); string s1 = Dir + FileTitle + FileExt; int j = 2; if (System.IO.File.Exists(s1)) { string s = string.Format("{0}{1}({2}){3}", Dir, FileTitle, j, FileExt); while (System.IO.File.Exists(s)) { j++; s = string.Format("{0}{1}({2}){3}", Dir, FileTitle, j, FileExt); } if (!System.IO.File.Exists(s)) SaveToFile(sText, s); return s; } else { SaveToFile(sText, s1); return s1; } } private void button1_Click(object sender, EventArgs e) { string s= CreateFile2("123", @"D:AdministratorDesktop9sity新建 文本文档.txt"); MessageBox.Show("已保存为:" + System.IO.Path.GetFileName(s) + " 文件路径:" + System.IO.Path.GetDirectoryName(s), "ROMAN提示",MessageBoxButtons.OK,MessageBoxIcon.Information); }