Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajkiran SwainRank #165 · 14.4K reputationPosted May 25, 2023, 12:49 AM EDT
using System.IO; using System.IO.Packaging; public bool IsFilePasswordProtected(string filePath) { try { using (Package package = Package.Open(filePath, FileMode.Open, FileAccess.Read)) { // Check if the package contains the encryption package relationship if (package.RelationshipExists(PackageRelationshipTypes.Encryption)) { return true; // File is password protected } } } catch (IOException) { // Handle any IO exceptions } catch (System.Security.Cryptography.CryptographicException) { // Handle cryptographic exceptions } return false; // File is not password protected or an error occurred }Naimish MakwanaRank #324 · 7.7K reputationPosted May 25, 2023, 1:10 AM EDT
Try below method:
public static bool IsPasswordProtected(string filePath, string password) { try { using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { // Try to open the file with the provided password using (StreamReader streamReader = new StreamReader(fileStream, false)) { streamReader.ReadToEnd(); // Read the file to validate the password } } // If the file was successfully opened and read, it is not password-protected return false; } catch (SecurityException) { // The file is password-protected return true; } catch (Exception) { // An exception occurred, which might indicate that the file is password-protected return true; } }Thanks
raj rajRank #5,629 · 292 reputationPosted May 25, 2023, 2:44 AM EDT
@rajkiran code is not working keyword PackageRelationshipTypes is unknown
raj rajRank #5,629 · 292 reputationPosted May 25, 2023, 3:09 AM EDT
Hi naimish your code is not working
Sam HobbsRank #107 · 20.5K reputationPosted May 26, 2023, 3:13 PM EDT
There is a Nuget package for System.IO.Packaging. I do not know if it is necessary to install that package. When I install it I then get an error saying PackageRelationshipTypes does not exist. Intellisense says I need to install an NPOI package and there are multiple NPOI packages. Therefore if the code provided by Rajkiran Swain works then I think we need an explanation of how to get the System.IO.Packaging namespace.