我在玩 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();
}
}
}
很抱歉,代码片段很长,但由于我不确定问题出在哪里,所以我必须包含几乎所有内容。