Check for password protected file with EPPlus ExcelPackage - c#

What is the correct way to check is an excel file is password protected (I do not know the password)? When I try to open it I get a non-specific exception ("A disk error occurred during a write operation.") that could be related to any other type of invalid file. Thanks

If I try to open a password protected xlsx file, I get the exception -
{"Can not open the package. Package is an OLE compound document. If this is an encrypted package, please supply the password"}
It also suggests using the overloaded method to open it
sample:
string mySpreadsheetName = #"path/to/file/name/xlsx";
FileInfo fi = new FileInfo(mySpreadsheetName);
ExcelPackage p1 = new ExcelPackage(fi, "abcd"); // this opens correctly, here "abcd" is the password
ExcelPackage p2 = new ExcelPackage(fi); //this throws an exception
Are you getting a different exception ?

Related

SharePoint 2016 Checkin using C# - FileNotFound Exception

I am using the below code to check-in a file to SharePoint 2016 using C#. But it is throwing Microsoft.SharePoint.Client.ServerException: File Not Found. The file URL is valid and file.name is printed in the console confirming its validity. Please advise what is going wrong here.
string url = "valid url of the file";
var file = clientContext.Web.GetFileByServerRelativeUrl(url);
clientContext.Load(file);
clientContext.ExecuteQuery();
Console.WriteLine(file.Name); //successfully printed expected result
file.CheckIn("Test", CheckinType.MajorCheckIn);
clientContext.Load(file);
clientContext.ExecuteQuery(); //File Not Found Exception thrown at this point
Try this:
using (ClientContext clientContext = GetContextObject())
{
string url = "valid url of the file";
var file = clientContext.Web.GetFileByServerRelativeUrl(url);
using (FileStream fs = new FileStream(file, FileMode.Open))
{
File.SaveBinaryDirect(clientContext, file, fs, true);
}
}
You might find that the "valid url of the file" is not actually valid. I am getting this error from a URL that is "valid" in the sense that opens the file in Sharepoint from the browser but I think the filename has some characters that the C# CSOM interface doesn't support. In my case the file is called "GetPDF.aspx%2F4AA3-8247ENW.pdf", so it's probably because it has two periods, but I'm struggling to confirm that.
You might take a look at https://www.codesharepoint.com/csom/get-checkin-comment-of-file-in-sharepoint-using-csom. I've never used CSOM and GetFileByServerRelativeUrl, but I seem to recall CheckIn has to occur on the file as opposed to the item containing the file.

WebClient.FileDownlOad GIVIn error that the file a is accessed by another process

I am trying to download a file using webclient method DownloadFile But its giving me error that
The process cannot access the file '...\d915877c-cb7c-4eeb-97d8-41d49b75aa27.docx' because it is being used by another process.
But when I open the file by clicking it, it opening.
There are same question requesting same info but none are accepted answers.
any help will be appreciated
It may be oS that is not letting file go. Whatever it is but after searching a lot I am unable to find solution
Here is the code to create a file
Document d = new Document();
d.Save(HttpContext.Current.Server.MapPath(#"Invoice\" + iname + ".docx"));
I am using aspose word dll
and following way I am accessing it
using (var client = new System.Net.WebClient())
{
client.UseDefaultCredentials = true;
client.DownloadFile(Server.MapPath("invoice/" + Request.QueryString["id"].ToString() + ".docx"),Server.MapPath("invoice/" +Request.QueryString["id"].ToString() + ".docx"));
client.Dispose();
}
and BTW its giving same error even to files that are not creaated using code.
Give a different path where to save the download file which is different from the download source path. If you want to replace the file do it after disposing the webclient by using File.replace() method.
string downloadPath = "Your download path";
string destinationPath = "the path where the file should be saved";`//this should be different from "download path"
File.Download(downloadPath,destinationPath);

NotSupportedException gets thrown

I am using C# to create a function to write data to a file in File System, and reate it and repeat function if file doesn't exist.
The first method of just writing the data is working. But the second method, if the file is not present and the program has to first create it, isn't working. It creates the file but at the very same time throws an exception to me in Visual Studio saying
System.NotSupportedException is unhandled
I am using the exact copy of code that the MSDN is having.
http://msdn.microsoft.com/en-us/library/d62kzs03(v=vs.110).aspx
Here is what I am using in my second code block,
// Create file!
using (FileStream fs = File.Create(file))
{
Byte[] info = new UTF8Encoding(true).GetBytes("some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
// Continue again with the request.
createFile(file);
The method declaration (if required) is as
private static void createFile (string fileName) {
string file = "C:\\Users\\AfzaalAhmad\\Documents\\" + fileName + ".txt";
/* two methods here */
}
The Image is as: (Note that there is no error in the path of file) I have used
Console.Write(file); // to get the path, and its OK!
See it in the image below ↓
Please note, that it does create the file in the Documents folder. But throws this exception. What am I doing wrong here?
Note the detail in the exception report: "The given path's format is not supported."
Also look at the contents of your variable file - it appears to be #"C:\Users\AfzaalAhmad\Documents\C:\Users..." - i.e. it contains the path twice.
So even though the operating system might have managed somehow to create some sort of file, the filename does not contain a valid value.
[edit] createFile(file); and Console.Write(file); are both taking the value #"C:\Users\AfzaalAhmad\Documents\dsg b.txt" but your method createFile is then adding the path a second time. Change it to simply:
private static void createFile (string file) {
/* two methods here */
}
Please have a exact look at the Exception message and the value of your file variable! There is your error!

Checking if file actually is an Excel file using EPPlus

I'm using EPPlus in C# to read an Excel (.xlsx) file. The initialization is done like this:
var package = new ExcelPackage(new FileInfo(filename));
This works fine but is there any way to check if the specified filename or package is actually a valid .xlsx file? Otherwise there will be exceptions when operating on a non-Excel object, e.g. if the user accidentially opens a .zip file or else.
You can check the extension of your file:
string file = #"C:\Users\Robert\Documents\Test.txt";
string extenstion = Path.GetExtension(file);
Update
I havent found some kind of return values for the situation that some file cannot be open in the EPPlus documentation, but you can use this to catch the excetptions:
FileInfo fileInfo = new FileInfo(pathToYourFile);
ExcelPackage package = null;
try
{
package = new ExcelPackage(fileInfo);
}
catch(Exception exception)
{
...
}
If you are not in catch - thats mean it was opened correctly.

How do I get the full filename for an Office document using C# and Office Interop?

In the following code, the second line throws an error that reads "Exception from HRESULT: 0x800A03EC". I suspect I'm getting a null for FullName. Can someone tell me what I'm doing wrong?
Foo.DataClasses1DataContext db = new Foo.DataClasses1DataContext();
string ThisDocument = Globals.ThisAddIn.Application.ThisWorkbook.FullName;
byte[] inputBuffer = System.IO.File.ReadAllBytes(ThisDocument);
Foo.RFP_Document rfpDocument = new MediaDesk.RFP_Document();
rfpDocument.DocumentName = "Foobar";
rfpDocument.DocumentFile = new System.Data.Linq.Binary(inputBuffer);
db.RFP_Documents.InsertOnSubmit(rfpDocument);
db.SubmitChanges();
For context, this is an Excel 2010 add-in written in C# targeting .NET 4.0. The objective of the code is to save the document to a database.
Use Globals.ThisAddIn.Application.ActiveWorkbook.FullName. From MSDN Globals.ThisAddIn.Application.ThisWorkBook returns the workbook where "Macro" is running. Since you don't have a macro this will throw an exception.

Categories