如何保存已经存在的文件?
How to save a file that already exists?
我将推出一个代码编辑器,供人们创建机器人来表达不同意见,它几乎已经准备就绪,但我需要帮助的是在保存文件时,我创建了一个保存但当文件已经存在的函数这个人必须替换,然后我创建了一个名为 currentFile 的字符串,它将存储所选文件的路径,然后如何让它只替换文件中的文本而不需要替换文件或打开保存菜单?
String currentFile = "C:\Program Files (x86)\EXAMPLE\FILE.js";
SaveFileDialog sfd = default(SaveFileDialog);
if (fctb_code.Text.Length > 0)
{
sfd = new SaveFileDialog();
//sfd.Filter = "All Files|*.*";
//sfd.DefaultExt = "html";
sfd.ShowDialog();
string location = currentFile;
string sourcecode = fctb_code.Text;
location = sfd.FileName;
if (!object.ReferenceEquals(sfd.FileName, ""))
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(location, false))
{
writer.Write(sourcecode);
writer.Dispose();
}
}
而且我希望当文件存在时它只是替换文件中的文本,但当它不存在时它将文件另存为新文件并打开 SaveFileDialog。
您在 sfd.ShowDialog();
下面发布的所有代码都可以用一个简单的命令(和一个 if 语句)替换
if (sfd.FileName != "")
{
System.IO.File.WriteAllText(currentFile, fctb_code.Text);
}
不需要 Streams 和 StreamWriters。没有迟钝的 if
逻辑。
引用the documentation for File.WriteAllText,这将为您覆盖:
Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
我将推出一个代码编辑器,供人们创建机器人来表达不同意见,它几乎已经准备就绪,但我需要帮助的是在保存文件时,我创建了一个保存但当文件已经存在的函数这个人必须替换,然后我创建了一个名为 currentFile 的字符串,它将存储所选文件的路径,然后如何让它只替换文件中的文本而不需要替换文件或打开保存菜单?
String currentFile = "C:\Program Files (x86)\EXAMPLE\FILE.js";
SaveFileDialog sfd = default(SaveFileDialog);
if (fctb_code.Text.Length > 0)
{
sfd = new SaveFileDialog();
//sfd.Filter = "All Files|*.*";
//sfd.DefaultExt = "html";
sfd.ShowDialog();
string location = currentFile;
string sourcecode = fctb_code.Text;
location = sfd.FileName;
if (!object.ReferenceEquals(sfd.FileName, ""))
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(location, false))
{
writer.Write(sourcecode);
writer.Dispose();
}
}
而且我希望当文件存在时它只是替换文件中的文本,但当它不存在时它将文件另存为新文件并打开 SaveFileDialog。
您在 sfd.ShowDialog();
下面发布的所有代码都可以用一个简单的命令(和一个 if 语句)替换
if (sfd.FileName != "")
{
System.IO.File.WriteAllText(currentFile, fctb_code.Text);
}
不需要 Streams 和 StreamWriters。没有迟钝的 if
逻辑。
引用the documentation for File.WriteAllText,这将为您覆盖:
Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.