---
title: "C# System.IO.FileStream 读取被其他程序打开的文件提示“文件正由另一进程使用，因此该进程无法访问该文件。”"
author: "NickWar"
date: "2009-12-09T16:34:00Z"
tags: []
slug: "c-system-io-filestream"
draft: false
lastmod: "2012-04-20T20:55:50Z"
id: 1492379
url: "https://nickwar.iteye.com/blog/1492379"
---

将文件转化为二进制代码时，出现提示：

文件正由另一进程使用，因此该进程无法访问该文件

原来是构造System.IO.FileStream时，使用的方法有问题

一开始是直接使用

System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open)

这个方法打开文件的时候是以只读共享的方式打开的，但若此文件已被一个拥有写权限的进程打开的话，就无法读取了，

因此需要使用

System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open,System.IO.FileAccess.Read,FileShare.ReadWrite);

设置文件共享方式为读写，FileShare.ReadWrite，这样的话，就可以打开了

附，把二进制转化为文件的函数

这两个函数经常用来存取数据库哦的BLOB字段。