C#异常。文件正被另一个进程使用 [英] C# exception. File is being used by another process

查看:162
本文介绍了C#异常。文件正被另一个进程使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C#玩弄,我遇到了一个问题。
当我尝试做一个新的文件,程序中断,并说该文件正被另一个进程。 !这可能是我忽略了一些愚蠢的事,但我不能弄明白

I'm playing around with C# and I encountered a problem. When I try to make a new file, the program breaks and says that the file is being used by another process. It's probably something stupid that I overlooked, but I cant figure it out!

下面是我的代码:

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();
        }
    }
}



对不起,长的代码段,但因为我不知道问题出在哪里来源于我必须包括几乎一切。

Sorry for the long code snippet, but since I'm not sure where the problem originates from I had to include pretty much everything.

推荐答案

您的问题是, File.Create 会打开让你做什么你喜欢的文件中的流:

Your problem is that File.Create will open a stream allowing you to do what you like to the file:

http://msdn.microsoft.com/en-us/library /d62kzs03.aspx

这提供读取路径指定的文件/写访问。使用FileStream

A FileStream that provides read/write access to the file specified in path.

因此,从技术上讲,它是在使用了。

Therefore, technically, it is in use already.

只需删除 File.Create 干脆。在的StreamWriter 将负责创建,如果它不存在该文件。

Just remove the File.Create altogether. The StreamWriter will handle creating the file if it doesn't exist.

此外,投资使用构建正确处理文件的连接了。将有助于避免这种情况在未来。

Also, invest in using constructs to properly dispose of your file connections too. Will help avoid this in the future.

这篇关于C#异常。文件正被另一个进程使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆