【问题标题】:Using FileStream to write to a file first time after the file is created gives an exception创建文件后第一次使用 FileStream 写入文件会出现异常
【发布时间】:2018-05-31 02:32:42
【问题描述】:

我正在尝试编写一些 json 文本。但我得到一个例外 该进程无法访问文件 C:\blah blah\SystemInActivity.json,因为它正被其他进程使用。但是当我在创建 json 文件后第二次运行应用程序时,然后当我编写时我没有得到异常。请帮忙。

class ApplicationSettingsViewModel
    {
        ApplicationSettingsModel model;
        MemoryMappedFile mmf = null;
        public string FullPath = string.Empty;
        //This is not a singleton class but I guess it has to be one but its ok for demonstration.
        public ApplicationSettingsViewModel()
        {
            model = new ApplicationSettingsModel();
            CreateFileWithoutMemoryMap();
            //MemoryMapped();
        }

        public string GetDriectory()
        {
            return Path.GetDirectoryName(FullPath);
        }

        private void CreateFileWithoutMemoryMap()
        {
            var info = Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "/" + model.Data.Settings.OrcaUISpecificSettings.TimeOutFolder);
            string path = Path.Combine(info.FullName + @"\" + model.Data.Settings.OrcaUISpecificSettings.File);
            //mmf = MemoryMappedFile.CreateFromFile(path, FileMode.CreateNew, "MyMemoryFile", 1024 * 1024, MemoryMappedFileAccess.ReadWrite);
            FullPath = path;
            if (!File.Exists(path))
            {
                File.Create(path);
            }
        }

        public void WriteToFile(string json)
        {
            try
            {
                FileStream fileStream = File.Open(FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //This line giving Exception
                fileStream.SetLength(0);
                fileStream.Close(); // This flushes the content, too.
                using (StreamWriter sw = new StreamWriter(FullPath))
                {
                    sw.Write(json);
                }
            }
            catch (Exception ex)
            {

            }
        }

在 MainWindow 的构造函数中,我调用了 write 方法

private ApplicationSettingsViewModel AppViewModel;
public MainWindow()
        {
            InitializeComponent();
            //MessageBox.Show("App Started");
            AppViewModel = new ApplicationSettingsViewModel();
            WriteToFile("Active");

        }
public void WriteToFile(string status)
        {
            var root = new Root();
            string jsonString = string.Empty;
            root.AllApplications.Add(new DataToWrite() { AppName = "DevOrca", Status = status });
            try
            {
                jsonString = JsonConvert.SerializeObject(root, Formatting.Indented);
            }
            catch (Exception ex)
            {
                MessageBox.Show(jsonString);
                MessageBox.Show("Exception");
            }
            mutex.WaitOne();
            //Serialize Contents and write
            AppViewModel.WriteToFile(jsonString);
            //var access = AppViewModel.GetAccessor();
            //byte[] bytes = Encoding.ASCII.GetBytes(jsonString);
            //access.Write(bytes, 0, bytes.Length);
            mutex.ReleaseMutex();
        }

【问题讨论】:

  • 您的代码不保证FileStream 将被关闭。使用using 块。你的try/finally 是错误的。永远不要吞下异常。
  • 永远不要相信自己,如果你可以使用using 语句,请使用它
  • 是的,我知道 try catch 是错误的。我并不担心,因为我知道异常来自哪里。我可以稍后修复它。
  • 感谢 Ken White 提供的链接。我会确保在需要的地方使用 using 语句。

标签: c# wpf file


【解决方案1】:

File.Create() 方法打开FileStream 来创建一个文件,你需要关闭它,像这样:

File.Create(path).Close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多