首页 / C# / C#-保存文件而不使用“保存文件”对话框
C#-保存文件而不使用“保存文件”对话框
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#-保存文件而不使用“保存文件”对话框,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1858字,纯文字阅读大概需要3分钟。
内容图文
![C#-保存文件而不使用“保存文件”对话框](/upload/InfoBanner/zyjiaocheng/656/0efadfb0d3b744b1b70f826763ebdc6a.jpg)
我仍在从事此项目,但遇到了问题.好吧,这是我需要做的.
When the user clicks the “Save” button, write the selected record to
the file specified in txtFilePath (absolute path not relative) without
truncating the values currently inside and handle any exceptions that arise.
好的,这是我的代码:
private void Save_Click(object sender, EventArgs e)
{
string filePath = txtFilePath.Text;
if (!File.Exists(filePath))
{
FileStream fs = File.Create(filePath);
fs.Close();
}
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (string line in employeeList.Items)
{
sw.WriteLine(line);
}
}
}
}
现在,当我进入程序并希望从employeelist.text中保存某些内容时,该内容未保存到我要保存的位置.我不知道我是否在代码中遗漏了什么或什么,但这将无法保存.这是一个例子:
I add a person name to this list in employeelist and in the textbox I
have a file called C:\employess\employeelist.txt I want to save it to.
I click the save button then I go to that employeelist and it is not
being saved.
我不知道自己在做错什么,我一直在网上寻找解决方案,但还没有发现任何东西.谢谢
解决方法:
需要仔细检查的一些事情:
>确保在测试时没有打开employeelist.txt文件
>确保文件名中没有无效字符
>确保您的应用程序有权将文件保存到您指定的位置
>使用调试器单步执行代码并查找可吞咽的异常-必须有未创建文件的原因.
>检查您的Save_Click事件是否已连接到按钮上-示例中的代码是否还在运行?
检查完这些内容后,您可能希望按照以下示例来满足项目的创建与附加要求:
string path = txtFilePath.Text;
// This text is added only once to the file.
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
foreach (var line in employeeList.Items)
sw.WriteLine(line.ToString());
}
}
else
{
using (StreamWriter sw = File.AppendText(path))
{
foreach (var line in employeeList.Items)
sw.WriteLine(line.ToString());
}
}
如果文件不存在,它将创建文件;如果文件不存在,则将添加文件.
内容总结
以上是互联网集市为您收集整理的C#-保存文件而不使用“保存文件”对话框全部内容,希望文章能够帮你解决C#-保存文件而不使用“保存文件”对话框所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。