我正在玩C#,我遇到了一个问题.当我尝试创建一个新文件时,程序会断开并说该文件正由另一个进程使用.这可能是我忽略的愚蠢,但我无法弄明白!
这是我的代码:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace myNameSpace
{
public partial class MainWindow : Form
{
public static string folderPath = @"fullpath";
public MainWindow()
{
InitializeComponent();
StoredTb.Text = folderPath;
String[] files = Directory.GetFiles(folderPath);
foreach (string file in files)
myDropDown.Items.Add(Path.GetFileNameWithoutExtension(file));
}
private void myDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
this.BeginInvoke(new MethodInvoker(myDropDown_invokedMethod));
}
private void myDropDown_invokedMethod()
{
string fullpath = MainWindow.folderPath + myDropDown.SelectedText + ".txt";
StreamReader sr = new StreamReader(fullpath);
NameTb.Text = myDropDown.SelectedText;
DescriptionTb.Text = sr.ReadToEnd();
sr.Close();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
File.Create(NameTb.Text + ".txt");
TextWriter tw = new StreamWriter(NameTb.Text + ".txt"); /* this is where the problem occurs */
tw.WriteLine("The very first line!");
tw.Close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
对于长代码片段感到抱歉,但由于我不确定问题源自何处,因此我必须包含很多内容.
Arr*_*ran 13
你的问题是File.Create打开一个stream允许你对文件做你喜欢的事情:
http://msdn.microsoft.com/en-us/library/d62kzs03.aspx
FileStream,提供对path中指定的文件的读/写访问权限.
因此,从技术上讲,它已经在使用中.
File.Create完全删除.StreamWriter如果文件不存在,它将处理创建文件.
此外,投资using构造以正确处理您的文件连接.将来有助于避免这种情况.