此代码在SaveFileDialog
private void buttonSaveAs_Click(object sender, EventArgs e)
{
try
{
if (selectedFileInfo != null)
{
// Save File
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = explorerTree2.SelectedPath;
// set a default file name
saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(selectedFileInfo.Name) + "-COPY" + selectedFileInfo.Extension;
// set filters - this can be done in properties as well
saveFileDialog1.Filter = "HTM files (*.htm)|*.htm|HTML files (*.html)|*.html|XML files (*.xml)|*.xml|Text files (*.txt)|*.txt|All files (*.*)|*.*";
#region Define filter index
if (selectedFileInfo.Extension.Equals(".htm")) // HTM files (*.htm)|*.htm
{
saveFileDialog1.FilterIndex = 1;
}
else // All files (*.*)|*.*
{
saveFileDialog1.FilterIndex = 5;
}
#endregion
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName))
{
sw.Write(scintilla1.Text);
sw.Flush();
sw.Close();
}
}
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
而另一个则没有。并且没有任何错误。任何线索?
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
if (selectedFileInfo != null)
{
using (FileStream fs = new FileStream(selectedFileInfo.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
StreamWriter sw = new StreamWriter(fs);
sw.AutoFlush = true;
sw.Write(scintilla1.Text);
sw.Flush();
sw.Close();
}
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
P.S。此选项不起作用
using (FileStream fs = new FileStream(selectedFileInfo.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.AutoFlush = true;
sw.Write(scintilla1.Text);
sw.Flush();
sw.Close();
}
}
答案 0 :(得分:0)
我找到了正确的解决方案
其中 scintilla1.Text 是您必须编写的字符串
selectedFileInfo 是FileInfo
个对象。在您的情况下, scintilla1.Text 可能类似于string
或RichTextBox
或任何其他文本编辑器控件。
private void buttonSave_Click(object sender, EventArgs e)
{
if (selectedFileInfo != null)
{
FileStream stream = null;
try
{
stream = selectedFileInfo.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
using (StreamWriter sw = new StreamWriter(stream))
{
sw.AutoFlush = true;
sw.Write(scintilla1.Text);
sw.Flush();
sw.Close();
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (stream != null)
stream.Close();
}
}
}