Open locked file with OpenXML in read only mode - c#

When I try to open a file that is locked, like this:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
... code stripped for clarity ...
// false stands for read only mode
spreadsheetDocument_ = SpreadsheetDocument.Open(fileName_, false);
I get this exception:
System.IO.IOException: 'The process cannot access the file 'file.xlsx' because it is being used by another process.'
Full stack trace:
System.IO.IOException
HResult=0x80070020
Message=The process cannot access the file 'file.xlsx' because it is being used by another process.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync)
at MS.Internal.IO.Zip.ZipArchive.OpenOnFile(String path, FileMode mode, FileAccess access, FileShare share, Boolean streaming)
at System.IO.Packaging.ZipPackage..ctor(String path, FileMode mode, FileAccess access, FileShare share, Boolean streaming)
at System.IO.Packaging.Package.Open(String path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.OpenCore(String path, Boolean readWriteMode)
at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(String path, Boolean isEditable, OpenSettings openSettings)
at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(String path, Boolean isEditable)
How can I open the file in read only mode and ignore the lock flag? I also want to avoid creating a lock flag if the file is not open in another program, so that the file can be edited further.

Try to passing a stream instead of string (file path). You can also use a File stream class to open the Excel file.
Console app snippet:
static void Main(string[] args)
{
using (var fileStream = new FileStream(#"path", FileMode.Open,FileAccess.Read, FileShare.ReadWrite))
{
using (var spreadSheetDocument = SpreadsheetDocument.Open(fileStream, false))
{
//Implementation
}
}
}
Source: OpenXML and opening a file in Read only mode

Related

Access Denied Error when using ZipFile Class

Background
I currently have a usb device which has all my projects which I am working on and it stays in my office's docking station. Last night I was bored and wanted to continue work on a project, However no files? This made me think about writing a console app that would copy all the files from my usb drive to a folder on my desktop and would run as a scheduled task at a certain hour.
Problem
I am trying to use a System.IO.Compression.FileSystem in order to compress the file in order in order to then move it to a new directory on my PC. The documentation gives an example here ZipFile class. IT seems very up front. However, when I am trying to copy it to a new destination I get the following error.
Error
Message
Access to the path 'C:\Users\er4505\Desktop' is denied.
StackTrace
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.Compression.ZipFile.Open(String archiveFileName, ZipArchiveMode mode, Encoding entryNameEncoding)
at System.IO.Compression.ZipFile.DoCreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName, Nullable`1 compressionLevel, Boolean includeBaseDirectory, Encoding entryNameEncoding)
at System.IO.Compression.ZipFile.CreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName)
at ConsoleApp1.Program.Main(String[] args) in C:\FTG\Projects\CaseWare\ConsoleApp1\Program.cs:line 25
Code
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string[] folders = System.IO.Directory.GetDirectories(#"D:\", "*", System.IO.SearchOption.TopDirectoryOnly);
foreach (string folder in folders)
{
ZipFile.CreateFromDirectory(folder, path); << errors out here!
}
The 2nd parameter string destinationArchiveFileName should be a filename.
for Example "C:\Users\er4505\Desktop\example.zip"

System.Unauthorized Exception

*
Exception =System.Net.WebException: Access to the path
'c:\windows\system32\inetsrv\Dialer' is denied. --->
System.UnauthorizedAccessException: Access to the path
'c:\windows\system32\inetsrv\Dialer' is denied. at
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess
access, Int32 rights, Boolean useRights, FileShare share, Int32
bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String
msgPath, Boolean bFromProxy, Boolean useLongPath) at
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess
access, FileShare share, Int32 bufferSize, FileOptions options, String
msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String
path, FileMode mode, FileAccess access, FileShare share) at
System.Net.FileWebStream..ctor(FileWebRequest request, String path,
FileMode mode, FileAccess access, FileShare sharing) at
System.Net.FileWebRequest.GetRequestStreamCallback(Object state)
--- End of inner exception stack trace --- at System.Net.WebClient.UploadDataInternal(Uri address, String method,
Byte[] data, WebRequest& request) at
System.Net.WebClient.UploadString(Uri address, String method, String
data)
*
Code where the exception is occurring
using (var writer = new StringWriter())
{
JsonSerializer.Create().Serialize(writer, payLoad);
var result =client.UploadString(commDialerApiUrl,writer.ToString());
return ((T)JsonConvert.DeserializeObject(result, typeof(T)));
}
I know the code above is not ideal, however I just need to understand why even an attempt to access is made. Can anyone provide some insight please?
All right, the issue was very simple. The code was trying to make a Restful post to a blank Uri. Since the Uri was blank webclient was trying to resolve the call to a file (having the same name as the service) in inetpub.
Since no such file path was invalid, thus the i/o error.

IIS 7 Access to the path is denied when trying to generate report

We are getting this error message upon trying to generate a report not accessing a file. We are using IIS 7.
XXX is located on a different server than the web server.
2014-10-24 11:04:13,287 [5] ERROR FOUNDATION [(null)] - Access to the path '\\XXX \file2022.pdf' is denied.
System.UnauthorizedAccessException: Access to the path '\\XXX\file.pdf' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.WriteStreamToFile(Stream stream, String filename)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportStreamToFile(Stream stream, DiskFileDestinationOptions options)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.Export(ExportRequestContext reqContext)
at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToDisk(ExportFormatType formatType, String fileName)
at GlobalFunctions.GenerateCrystalReport(String reportFileName, String outputFileName, List`1 params) in C:\NetProjects\branches\R7\GUIs\Foundation\App_Code\GlobalFunctions.vb:line 347
If you must access files like this make sure your Application Pool is running as a domain user with read permission to that location.

Write on Excel file while it is open by another user

I'm trying to edit an opened excel file (by another user in a shared network) in order to make some changes to it and save it back. But when I try to open the file I get the following error :
Message=The process cannot access the file
'Y:\COMMON\SharedFolders\Export.xlsx', because it is being used by another process.
Source=mscorlib
StackTrace:
à System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
à System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
à System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
à System.IO.File.InternalReadAllBytes(String path, Boolean checkHost)
à System.IO.File.ReadAllBytes(String path)
à OfficeOpenXml.ExcelPackage.ReadFile()
à OfficeOpenXml.ExcelPackage.ConstructNewFile(Stream stream, String password)
à OfficeOpenXml.ExcelPackage..ctor(FileInfo newFile)
By the way, I'm using the EPPLUS library.
You can't. That being said you can look into some "source-safe" solution (like svn, sharepoint or google docs). You can also implement some "poor man" source safe yourself - i.e. small web application that will act as proxy over file system & will allow you to upload file, list folder, download files.
Other option would be to delay update to date when no-one will be accessing that file.
Google allow multiple edit at the same time... maybe you should try to move that file there if possible.

Not able to upload a file on server

I am trying to upload an image.it works fine when i do it from my localhost but when i published it it throw an error from server:
When I use this code :
public string ImagePath(HttpPostedFileBase imgfile)
{
var path = "";
// code for saving the image file to a physical location.
var fileName = Path.GetFileName(imgfile.FileName);
path = Path.Combine(HttpContext.Server.MapPath("~/Images/Sections/Developer/ClientLogo"), fileName);
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(imgfile.FileName);
int iteration = 1;
while (System.IO.File.Exists((path)))
{
fileName = string.Concat(fileNameWithoutExtension, "-", iteration, System.IO.Path.GetExtension(imgfile.FileName));
path = Path.Combine(HttpContext.Server.MapPath("~/Images/Sections/Developer/ClientLogo"), fileName);
iteration++;
}
imgfile.SaveAs(path);
// prepare a relative path to be stored in the database and used to display later on.
path = Url.Content(Path.Combine("~/Images/Sections/Developer/ClientLogo", fileName));
return path;
}
Error is
System.UnauthorizedAccessException: Access to the path 'D:\InetPub\vhosts\xx.com\httpdocs\Images\Sections\Developer\ClientLogo\circle-small-empty.18x18.png' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename) at System.Web.HttpPostedFileWrapper.SaveAs(String filename) at xx.CorporateSite.Controllers.DeveloperController.ImagePath(HttpPostedFileBase imgfile)
And when I use Server.MapPath instead of HttpContext.Server.MapPath it throw different error:
Error is:
System.IO.DirectoryNotFoundException: Could not find a part of the path 'D:\InetPub\vhosts\xx.com\httpdocs\Images\Sections\Developer\ClientLogo\demo.png'. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename) at System.Web.HttpPostedFileWrapper.SaveAs(String filename) at xx.CorporateSite.Controllers.DeveloperController.ImagePath(HttpPostedFileBase imgfile)
I tried to change the permission from my localhost but nothing is working...Please suggest me something
Your web application does not have permission to write to the location where you're trying to save the image. This is often handled by adding an entry to your web.config which points to a folder where all uploads are saved
<appSettings>
...
<add key="uploadPath" value="C:\Uploads"/>
...
</appSettings>
and then in your code you would read that configuration entry to identify the path where the image will be saved:
....
string path = ConfigurationManager.AppSettings["uploadPath"];
string filePath = Path.Combine(path, fileName);
....
And then in order to save the files to this directory, you would need to set permissions on the directory so that the user that the web application is running as has Write permissions on that directory. This will allow you to write files from the web application to that folder.
This way, you, as the developer, are not dictating where the files go. The system administrator can decide both where the files go, and what permissions are necessary to support your web application.
Check to see if the folder's Read-Only attribute is active. If it is uncheck it in the properties of the folder if this is a windows machine.
If it keeps reverting you may need to take ownership of the folder by going to security->advanced->effective permissions->click select...->put in your username and check full control->then click ok out.

Categories

Resources