public static void Main() { //创建文件 IO 读取权限 FileIOPermission FileIOReadPermission = new FileIOPermission(PermissionState.None); FileIOReadPermission.AllLocalFiles = FileIOPermissionAccess.Read; //创建基本权限集 PermissionSet BasePermissionSet = new PermissionSet(PermissionState.None); // PermissionState.Unrestricted 用于完全信任 BasePermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); PermissionSet grantset = BasePermissionSet.Copy(); grantset.AddPermission(FileIOReadPermission); //编写示例源文件以读取 System.IO.File.WriteAllText("TEST.TXT", "File Content"); //-------- 完全信任地调用方法 -------- try { Console.WriteLine("App Domain Name: " + AppDomain.CurrentDomain.FriendlyName); ReadFileMethod(); } catch (Exception ex) { Console.WriteLine(ex.Message); } //-------- 创建具有文件 IO 读取权限的 AppDomain -------- AppDomain sandbox = AppDomain.CreateDomain("Sandboxed AppDomain With FileIO.Read permission", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation, grantset, null); try { Console.WriteLine("App Domain Name: " + AppDomain.CurrentDomain.FriendlyName); sandbox.DoCallBack(new CrossAppDomainDelegate(ReadFileMethod)); } catch (Exception ex) { Console.WriteLine(ex.Message); } //-------- 创建没有文件 IO 读取权限的 AppDomain -------- //应当引发安全异常 PermissionSet grantset2 = BasePermissionSet.Copy(); AppDomain sandbox2 = AppDomain.CreateDomain("Sandboxed AppDomain Without FileIO.Read permission", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation, grantset2, null); try { Console.WriteLine("App Domain Name: " + AppDomain.CurrentDomain.FriendlyName); sandbox2.DoCallBack(new CrossAppDomainDelegate(ReadFileMethod)); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine(""); Console.WriteLine("Press any key to end."); Console.ReadKey(); }
public override void Initialize(string name, NameValueCollection config) { // Verify that config isn't null if (config == null) throw new ArgumentNullException("config"); // Assign the provider a default name if it doesn't have one if (String.IsNullOrEmpty(name)) name = "TextFileWebEventProvider"; // Add a default "description" attribute to config if the // attribute doesn't exist or is empty if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Text file Web event provider"); } // Call the base class's Initialize method base.Initialize(name, config); // Initialize _LogFileName and make sure the path // is app-relative string path = config["logFileName"]; if (String.IsNullOrEmpty(path)) throw new ProviderException ("Missing logFileName attribute"); if (!VirtualPathUtility.IsAppRelative(path)) throw new ArgumentException ("logFileName must be app-relative"); string fullyQualifiedPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (HttpRuntime.AppDomainAppVirtualPath), path); _LogFileName = HostingEnvironment.MapPath(fullyQualifiedPath); config.Remove("logFileName"); // Make sure we have permission to write to the log file // throw an exception if we don't FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, _LogFileName); permission.Demand(); // Throw an exception if unrecognized attributes remain if (config.Count > 0) { string attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) throw new ProviderException ("Unrecognized attribute: " + attr); } }
public static void FileIOPermissionCallMethods() { FileIOPermissionAccess fiopa = new Permissions.FileIOPermissionAccess(); FileIOPermission fiop = new FileIOPermission(fiopa, "testpath"); FileIOPermission fiop2 = new FileIOPermission(new Permissions.PermissionState()); fiop.AddPathList(fiopa, "testpath"); fiop.AddPathList(fiopa, new string[1] { "testpath" }); IPermission ip = fiop.Copy(); fiop.Equals(new object()); int hash = fiop.GetHashCode(); string[] pathlist = fiop.GetPathList(fiopa); IPermission ip2 = fiop.Intersect(ip); fiop.IsSubsetOf(ip); bool isunrestricted = fiop.IsUnrestricted(); fiop.SetPathList(fiopa, "testpath"); fiop.SetPathList(fiopa, new string[1] { "testpath" }); IPermission ip3 = fiop.Union(ip); SecurityElement se = new SecurityElement(""); fiop.FromXml(se); se = fiop.ToXml(); }
public void Read() { string filename = Assembly.GetCallingAssembly().Location; FileIOPermissionAttribute attr = new FileIOPermissionAttribute(SecurityAction.Assert); attr.Read = filename; Assert.IsNull(attr.Append, "Append=null"); Assert.IsNull(attr.PathDiscovery, "PathDiscovery=null"); Assert.AreEqual(filename, attr.Read, "Read=Read"); Assert.IsNull(attr.Write, "Write=null"); #if NET_2_0 Assert.IsNotNull(attr.AllFiles, "AllFiles"); Assert.IsNotNull(attr.AllLocalFiles, "AllLocalFiles"); Assert.IsNull(attr.ChangeAccessControl, "ChangeAccessControl"); Assert.IsNull(attr.ViewAccessControl, "ViewAccessControl"); #endif FileIOPermission p = (FileIOPermission)attr.CreatePermission(); filename = Path.GetFullPath(filename); Assert.IsNull(p.GetPathList(FileIOPermissionAccess.Append), "PathDiscovery=FileIOPermissionAttribute-Append"); Assert.IsNull(p.GetPathList(FileIOPermissionAccess.PathDiscovery), "PathDiscovery=FileIOPermissionAttribute-PathDiscovery"); Assert.AreEqual(filename, p.GetPathList(FileIOPermissionAccess.Read) [0], "PathDiscovery=FileIOPermissionAttribute-Read"); Assert.IsNull(p.GetPathList(FileIOPermissionAccess.Write), "PathDiscovery=FileIOPermissionAttribute-Write"); }
public void Intersect() { p = new FileIOPermission(FileIOPermissionAccess.Read, pathArrayGood); p.AllFiles = FileIOPermissionAccess.Append; p.AllLocalFiles = FileIOPermissionAccess.Write; unrestricted = new FileIOPermission(PermissionState.Unrestricted); FileIOPermission intersection = (FileIOPermission)p.Intersect(unrestricted); pathsInPermission = intersection.GetPathList(FileIOPermissionAccess.Read); Assert.IsTrue(pathsInPermission.Length == 2, "Should contain correct number of Read paths. Expected 2 but got: " + pathsInPermission.Length); Assert.IsTrue((intersection.AllFiles & FileIOPermissionAccess.Append) != 0, "Should have Append bit in AllFiles."); Assert.IsTrue((intersection.AllLocalFiles & FileIOPermissionAccess.Write) != 0, "Should have Write bit in AllLocalFiles."); intersection = (FileIOPermission)unrestricted.Intersect(p); pathsInPermission = intersection.GetPathList(FileIOPermissionAccess.Read); Assert.IsTrue(pathsInPermission.Length == 2, "Should contain correct number of Read paths. Expected 2 but got: " + pathsInPermission.Length); Assert.IsTrue((intersection.AllFiles & FileIOPermissionAccess.Append) != 0, "Should have Append bit in AllFiles."); Assert.IsTrue((intersection.AllLocalFiles & FileIOPermissionAccess.Write) != 0, "Should have Write bit in AllLocalFiles."); p2 = new FileIOPermission(FileIOPermissionAccess.Append | FileIOPermissionAccess.Read, pathArrayGood2); p2.AllFiles = FileIOPermissionAccess.Append | FileIOPermissionAccess.Write; p2.AllLocalFiles = FileIOPermissionAccess.Write | FileIOPermissionAccess.Read; intersection = (FileIOPermission)p.Intersect(p2); pathsInPermission = intersection.GetPathList(FileIOPermissionAccess.Read); Assert.IsNotNull(pathsInPermission, "Should have some paths"); Assert.AreEqual(2, pathsInPermission.Length, "Should contain correct number of Read paths"); Assert.AreEqual(FileIOPermissionAccess.Append, intersection.AllFiles, "Should have only Append bit in AllFiles."); Assert.AreEqual(FileIOPermissionAccess.Write, intersection.AllLocalFiles, "Should have only Write bit in AllLocalFiles."); intersection = (FileIOPermission)p2.Intersect(p); pathsInPermission = intersection.GetPathList(FileIOPermissionAccess.Read); Assert.IsTrue(pathsInPermission.Length == 2, "Should contain correct number of Read paths. Expected 2 but got: " + pathsInPermission.Length); Assert.IsTrue(intersection.AllFiles == FileIOPermissionAccess.Append, "Should have only Append bit in AllFiles."); Assert.IsTrue(intersection.AllLocalFiles == FileIOPermissionAccess.Write, "Should have only Write bit in AllLocalFiles."); }
//Madan Saini 09/26/2006 - This Method will be used for Logging the successful Logins from Notes Login Screen. //Starting with - PegOiReview. public static void RecordLogin(string Username, string Email, string IPAddress, string WebsiteName) { DataSet dsXML = new ERRORS(); string dstPath = ""; dstPath = Utilities.getDrivePathByLetter("ERRORLOG:"); dstPath += "\\UserHistory.xml"; try { // Create a file permission set indicating all of this method's intentions. FileIOPermission fp = new FileIOPermission(FileIOPermissionAccess.AllAccess, Path.GetFullPath(dstPath)); fp.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, Path.GetFullPath(dstPath)); // Verify that we can be granted all the permissions we'll need. fp.Demand(); // Assert the desired permissions here. fp.Assert(); //Now add the record to xml table for History if (System.IO.File.Exists(dstPath)) { dsXML.ReadXml(dstPath); DataRow Row = dsXML.Tables["UserLogins"].NewRow(); object[] myRowArray = new object[5]; myRowArray[0] = Username.Trim().ToUpper(); myRowArray[1] = Email.Trim().ToLower(); myRowArray[2] = IPAddress.Trim(); myRowArray[3] = System.DateTime.Now; myRowArray[4] = WebsiteName.Trim(); Row.ItemArray = myRowArray; dsXML.Tables["UserLogins"].Rows.Add(Row); dsXML.AcceptChanges(); dsXML.WriteXml(dstPath); } } catch (System.Exception ex) { GSA.R7BD.Utility.EventLog.WriteEntry("EventLog.cs", "GSA.R7BD.POIRBiz", "RecordLogin", "Error Occurred in RecordLogin procedure for User :"******" email: " + Email + ". The exception is: " + ex.Source + ex.Message, GSA.R7BD.Utility.EventLog.LogType.XMLFile); } }//end of this method
private static void InternalDelete(String fullPath, String userPath, bool recursive) { String demandPath; // If not recursive, do permission check only on this directory // else check for the whole directory structure rooted below demandPath = GetDemandDir(fullPath, !recursive); // Make sure we have write permission to this directory FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, demandPath, false, false); String longPath = Path.AddLongPathPrefix(fullPath); // Do not recursively delete through reparse points. Perhaps in a // future version we will add a new flag to control this behavior, // but for now we're much safer if we err on the conservative side. // This applies to symbolic links and mount points. Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = File.FillAttributeInfo(longPath, ref data, false, true); if (dataInitialised != 0) { // Ensure we throw a DirectoryNotFoundException. if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND) { dataInitialised = Win32Native.ERROR_PATH_NOT_FOUND; } __Error.WinIOError(dataInitialised, fullPath); } if (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0) { recursive = false; } DeleteHelper(longPath, userPath, recursive, true); }
internal static PermissionSet ExtractAppDomainPermissionSetMinusSiteOfOrigin() { PermissionSet permissionSetAppDomain = new PermissionSet(PermissionState.Unrestricted); // Ensure we remove the FileIO read permission to site of origin. // We choose to use unrestricted here because it does not matter // matter which specific variant of Fileio/Web permission we use // since we are using an overload to check and remove permission // that works on type. There is not a way to remove some // part of a permission, although we could remove this and add // back the delta if the existing permission set had more than the ones // we care about but it is really the path we are targeting here since // that is what causes the delta and hence we are removing it all together. Uri siteOfOrigin = SiteOfOriginContainer.SiteOfOrigin; CodeAccessPermission siteOfOriginReadPermission = null; if (siteOfOrigin.Scheme == Uri.UriSchemeFile) { siteOfOriginReadPermission = new FileIOPermission(PermissionState.Unrestricted); } else if (siteOfOrigin.Scheme == Uri.UriSchemeHttp) { siteOfOriginReadPermission = new WebPermission(PermissionState.Unrestricted); } if (siteOfOriginReadPermission != null) { if (permissionSetAppDomain.GetPermission(siteOfOriginReadPermission.GetType()) != null) { permissionSetAppDomain.RemovePermission(siteOfOriginReadPermission.GetType()); // Failing on a ReadOnlyPermissionSet here? // (Ctrl+X to cut text in RichTextBox // in an XBAP throws InvalidOperationException) } } return(permissionSetAppDomain); }
internal static bool Exists(string path) { try { if (path == null) { return(false); } if (path.Length == 0) { return(false); } path = LongPath.NormalizePath(path); if (path.Length > 0 && Path.IsDirectorySeparator(path[path.Length - 1])) { return(false); } FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, path, false, false); return(LongPathFile.InternalExists(path)); } catch (ArgumentException) { } catch (NotSupportedException) { } catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return(false); }
/// <summary> /// Blacklist a series of assemblies by setting their assemblies to zero length /// files. This is a way of ensuring that we don't load them again, or replace them /// with fresh working copies because the file name gets reserved with an invalid assembly. /// </summary> /// <param name="assemblies">The assemblies to be blacklisted.</param> public void BlacklistAssemblies(string[] assemblies) { // Ensure that the caller can't pass us a name that actually makes this file get created somewhere else var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] { AssemblyDirectory }); try { permission.PermitOnly(); if (assemblies != null) { foreach (var assembly in assemblies) { var fileName = GetFileName(assembly); try { // Replace this file with a zero length file (or create one), so we won't get it again using (var stream = File.Create(fileName)) { stream.Close(); } } catch (Exception e) { Debug.WriteLine("Error blacklisting organism:"); ErrorLog.LogHandledException(e); } } } } finally { CodeAccessPermission.RevertPermitOnly(); } }
public static bool CopyFile(string newFile, string oldFile) { var newfile = new FileInfo(newFile); var oldfile = new FileInfo(oldFile); string errorMsg = ""; var f2 = new FileIOPermission(FileIOPermissionAccess.AllAccess, oldFile); f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, newFile); try { f2.Demand(); } catch (SecurityException s) { Console.WriteLine(s.Message); } for (int x = 0; x < 100; x++) { try { File.Delete(oldfile.FullName); newfile.CopyTo(oldfile.FullName, true); return(true); } catch (Exception e) { errorMsg = e.Message + " : " + e.InnerException; Thread.Sleep(200); } } Data.Logger(errorMsg); return(false); }
//Determines if a package has a local version that can be deleted and is out of date. private bool IsPackageUpdateable(IPackage pack) { // Is there a local version? var ext = App.GetExtension(pack.Id); if (ext == null) { return(false); } //Checks if current version is greater than or equal to posted version, return false if true. //Assumes that version numbers in assembly files are accurate (not currently true). SemanticVersion extVersion = SemanticVersion.Parse(ext.Version); if (extVersion >= pack.Version) { return(false); } string assemblyLocation = GetExtensionPath(ext); // The original file may be in a different location than the extensions directory. During an update, the // original file will be deleted and the new package will be placed in the packages folder in the extensions // directory. FileIOPermission deletePermission = new FileIOPermission(FileIOPermissionAccess.Write, assemblyLocation); try { deletePermission.Demand(); } catch (SecurityException) { return(false); } return(true); }
public void MoveTo(string destFileName) { if (destFileName == null) { throw new ArgumentNullException("destFileName"); } if (destFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); } string fullPathInternal = Path.GetFullPathInternal(destFileName); FileIOPermission.QuickDemand(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, this.FullPath, false, false); FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPathInternal, false, false); if (!Win32Native.MoveFile(this.FullPath, fullPathInternal)) { __Error.WinIOError(); } this.FullPath = fullPathInternal; this.OriginalPath = destFileName; this._name = Path.GetFileName(fullPathInternal); base.DisplayPath = this.GetDisplayPath(destFileName); this._dataInitialised = -1; }
//------------------------------------------ public static void Write(string msg) { if (LogFileName != null) { try { FileIOPermission f = new FileIOPermission(FileIOPermissionAccess.AllAccess, LogFileName); string path = LogFileName.Substring(0, LogFileName.LastIndexOf("\\") + 1); string[] pathlist = { path }; f.AddPathList(FileIOPermissionAccess.AllAccess, pathlist); FileStream fs = new FileStream(LogFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter w = new StreamWriter(fs); // create a stream writer w.BaseStream.Seek(0, SeekOrigin.End); // to the end of file w.Write("{0}: {1}\r\n", DateTime.Now.ToString(), msg); w.Flush(); // update underlying file fs.Close(); } catch { LogFileName = null; // disable logging throw new Exception(excpMessage); } } }
private static void InternalDelete(string fullPath, string userPath, bool recursive) { string demandDir = LongPathDirectory.GetDemandDir(fullPath, !recursive); FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, demandDir, false, false); string text = Path.AddLongPathPrefix(fullPath); Win32Native.WIN32_FILE_ATTRIBUTE_DATA win32_FILE_ATTRIBUTE_DATA = default(Win32Native.WIN32_FILE_ATTRIBUTE_DATA); int num = File.FillAttributeInfo(text, ref win32_FILE_ATTRIBUTE_DATA, false, true); if (num != 0) { if (num == 2) { num = 3; } __Error.WinIOError(num, fullPath); } if ((win32_FILE_ATTRIBUTE_DATA.fileAttributes & 1024) != 0) { recursive = false; } LongPathDirectory.DeleteHelper(text, userPath, recursive, true); }
public void AddEditCuntry() { FileIOPermission f = new FileIOPermission(PermissionState.Unrestricted); //handle permissons f.AllLocalFiles = FileIOPermissionAccess.Read; //set the permissons. string filename = "countries.csv"; string CountryDetails = NametextBox.Text + ", " + GDPBoxInput.Text + ", " + InflationTextBox.Text + ", " + TradeBalInput.Text + ", " + HDIInput.Text + ", " + TradePartnerDropDown.Text; if (!File.Exists(filename)) //if the file does not exist { String countryHeader = "Country" + "GDP Growth" + "Inflation" + "Trade Balance" + "HDI Ranking" + "Main Trade Partners"; //header of the CSV file try { f.Demand(); //try to force the file to load File.WriteAllText(filename, countryHeader); //write to the file name with the country header. } catch (SecurityException s) { Console.WriteLine(s.Message); //catch any secuirty Exceptions } } String[] tradepartner = new String[1]; tradepartner[0] = TradePartnerDropDown.Text; Country country = new Country(NametextBox.Text, Convert.ToDouble(GDPBoxInput.Text), Convert.ToDouble(InflationTextBox.Text), Convert.ToDouble(TradeBalInput.Text), Convert.ToDouble(HDIInput.Text), tradepartner); AVLtree.InsertItem(country); //put the country item into the avl tree File.AppendAllText(filename, CountryDetails); //Append all text into the end of the CSV file Console.WriteLine(NametextBox.Text); getHiehgt(); //update tree height countryNumber(); //update number of countrys }
internal static long GetLength(String path) { Contract.Requires(path != null); String fullPath = LongPath.NormalizePath(path); FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); String tempPath = Path.AddLongPathPrefix(fullPath); Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = File.FillAttributeInfo(tempPath, ref data, false, true); // return error if (dataInitialised != 0) { __Error.WinIOError(dataInitialised, path); // from FileInfo. } if ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0) { __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, path); } return(((long)data.fileSizeHigh) << 32 | ((long)data.fileSizeLow & 0xFFFFFFFFL)); }
public static void CopyFile(String srcPath, String dstPath) { // Create a file permission set indicating all of this method's intentions. FileIOPermission fp = new FileIOPermission(FileIOPermissionAccess.Read, Path.GetFullPath(srcPath)); fp.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, Path.GetFullPath(dstPath)); // Verify that we can be granted all the permissions we'll need. fp.Demand(); // Assert the desired permissions here. fp.Assert(); // For the remainder of this method, demands for source file read access // and demands for destination file write/append access will be granted // immediately; walking the remainder of the stack will not be necessary. FileInfo srcFile = new FileInfo(srcPath); FileInfo dstFile = new FileInfo(dstPath); Stream src = srcFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read); Stream dst = dstFile.Open(FileMode.Create, FileAccess.Write, FileShare.None); // Note: FileInfo.Length is a Int64, but the Stream.Read and .Write // take Int32 counts - hence the casting/throttling necessary below if (srcFile.Length > Int32.MaxValue) { throw new ArgumentOutOfRangeException("CopyFile requires that the source file be less than 2GB."); } Byte[] buffer = new Byte[(Int32)srcFile.Length]; src.Read(buffer, 0, (Int32)srcFile.Length); dst.Write(buffer, 0, (Int32)srcFile.Length); src.Close(); dst.Close(); // We do not need a RevertAssert here because we are going out of scope }
private void ReportGrid_Load(object sender, EventArgs e) { if (DataSet != null) { DataSet.DataSetName = TableName; var rdlc = RdlcHelper.BuildRDLCStream( DataSet, TableName, Resources.report); //Fix for VS "15" permission issue var permissionSet = new PermissionSet(PermissionState.Unrestricted); var fIOPermission = new FileIOPermission(PermissionState.None); fIOPermission.AllLocalFiles = FileIOPermissionAccess.Read; permissionSet.AddPermission(fIOPermission); permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); reportView.LocalReport.SetBasePermissionsForSandboxAppDomain(permissionSet); reportView.LocalReport.LoadReportDefinition(rdlc); reportView.LocalReport.DataSources.Clear(); reportView.LocalReport.DataSources.Add( new ReportDataSource(DataSet.DataSetName, DataSet.Tables[0])); reportView.RefreshReport(); } }
public void CrearJsonUsuarios(T _user, HttpServerUtilityBase SERVIDOR) { string archivoJson; archivoJson = JsonConvert.SerializeObject(_user); string[] arreglo = archivoJson.Split(','); archivoJson = "{"; for (int i = 19; i < 23; i++) { archivoJson = archivoJson + arreglo[i] + ","; } archivoJson = archivoJson + arreglo[23] + "} ;"; JsonUsuarios = JsonUsuarios + archivoJson; string NombreArchivo = @"C:\Users\Public\Usuarios.json"; string path = Path.GetPathRoot(NombreArchivo); FileIOPermission permiso = new FileIOPermission(FileIOPermissionAccess.Write, path); foreach (string f in Directory.GetFiles(@"C:\Users\Public")) { if (NombreArchivo == f) { File.Delete(@"C:\Users\Public\Usuarios"); } } try { permiso.Demand(); StreamWriter escritor = new StreamWriter(NombreArchivo); escritor.WriteLine(JsonUsuarios); escritor.Close(); } catch { throw new Exception("Acceso denegado para el disco"); } }
public void AddPathListStringArray() { p = new FileIOPermission(FileIOPermissionAccess.Read, pathArrayGood); pathsInPermission = p.GetPathList(FileIOPermissionAccess.Read); Assert.IsTrue(pathsInPermission.Length == 2, "Does not contain correct number of paths. Expected 2 but got: " + pathsInPermission.Length); foreach (string s in pathsInPermission) { Assert.IsTrue(Array.IndexOf(pathsInPermission, s) >= 0, "Unexpected path in the Permission: " + s); } p.AddPathList(FileIOPermissionAccess.Append, pathArrayGood); pathsInPermission = p.GetPathList(FileIOPermissionAccess.Read); Assert.IsTrue(pathsInPermission.Length == 2, "Should still contain correct number Read paths. Expected 2 but got: " + pathsInPermission.Length); foreach (string s in pathsInPermission) { Assert.IsTrue(Array.IndexOf(pathsInPermission, s) >= 0, "Unexpected path in the Permission: " + s); } pathsInPermission = p.GetPathList(FileIOPermissionAccess.Append); Assert.IsTrue(pathsInPermission.Length == 2, "Should contain correct number of Append paths. Expected 2 but got: " + pathsInPermission.Length); foreach (string s in pathsInPermission) { Assert.IsTrue(Array.IndexOf(pathsInPermission, s) >= 0, "Unexpected path in the Permission: " + s); } }
public void SetUp() { Environment.CurrentDirectory = Path.GetTempPath(); filename = Path.GetTempFileName(); int os = (int)Environment.OSVersion.Platform; unix = ((os == 4) || (os == 128) || (os == 6)); p = null; pathsInPermission = null; pathArrayGood = new string[2]; pathArrayBad = new string[2]; pathArrayGood2 = new string[3]; // FIXME: Adjust to run on Mac OS's if (Path.VolumeSeparatorChar == ':') { pathArrayGood[0] = "c:\\temp1"; pathArrayGood[1] = "d:\\temp2"; pathArrayBad[0] = "c:\\temp1"; pathArrayBad[1] = "d:\\temp*"; pathArrayGood2[0] = "c:\\temp1"; pathArrayGood2[1] = "d:\\temp2"; pathArrayGood2[2] = "z:\\something"; } else { pathArrayGood[0] = "/temp1"; pathArrayGood[1] = "/usr/temp2"; pathArrayBad[0] = "/temp1"; pathArrayBad[1] = "/usr/temp*"; // not really bad under Unix... pathArrayGood2[0] = "/temp1"; pathArrayGood2[1] = "/usr/temp2"; pathArrayGood2[2] = "/usr/bin/something"; } }
private void CheckLimilabsLicence() { try { String fileName = LicenseHelper.GetLicensePath(); FileIOPermission x = new FileIOPermission(FileIOPermissionAccess.Read, LicenseHelper.GetLicensePath()); x.Assert(); var status = LicenseHelper.GetLicenseStatus(); FileLogger.Debug(Name, string.Format("File di licenza Mail.dll [{0}] in stato [{1}].", fileName, status)); if (!Parameters.IgnoreLimilabsLicence) { switch (status) { case LicenseStatus.Invalid: throw new Exception("Licenza Mail.dll non valida."); case LicenseStatus.NoLicenseFile: throw new Exception("Licenza Mail.dll non trovata: " + fileName); case LicenseStatus.Valid: FileLogger.Info(Name, "Licenza Mail.dll valida."); break; } } else { FileLogger.Info(Name, string.Format("Stato licenza Mail.dll: [{0}] ignorato.", status)); } } catch (Exception ex) { FileLogger.Error(Name, "Errore in [CheckLimilabsLicence].", ex); SendMessage(string.Format("Errore in [CheckLimilabsLicence]. \nErrore: {0} \nStacktrace: {1}", ex.Message, FullStacktrace(ex))); } }
internal static FileIOPermission GetGlobalFileIOPerm( IsolatedStorageScope scope) { if (IsRoaming(scope)) { // no sync needed, ok to create multiple instances. if (s_PermRoaming == null) { s_PermRoaming = new FileIOPermission( FileIOPermissionAccess.AllAccess, GetRootDir(scope)); } return(s_PermRoaming); } // no sync needed, ok to create multiple instances. if (s_PermUser == null) { s_PermUser = new FileIOPermission( FileIOPermissionAccess.AllAccess, GetRootDir(scope)); } return(s_PermUser); }
public override void Delete() { #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, DisplayPath, FullPath); state.EnsureState(); #else // For security check, path should be resolved to an absolute path. FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, FullPath, false, false); #endif bool r = Win32Native.DeleteFile(FullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) { return; } else { __Error.WinIOError(hr, DisplayPath); } } }
public async Task Traverse(string rootDirectory) { IEnumerable <string> files = Enumerable.Empty <string>(); IEnumerable <string> directories = Enumerable.Empty <string>(); try { // The test for UnauthorizedAccessException. var permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, rootDirectory); permission.Demand(); files = Directory.GetFiles(rootDirectory); directories = Directory.GetDirectories(rootDirectory); } catch { // Ignore folder (access denied). } try { foreach (var file in files) { Allfiles.Enqueue(file); } foreach (var item in directories) { await Task.Run(() => Thread.Sleep(3000)).ConfigureAwait(true); _ = Traverse(item); } } catch (Exception) { } }
internal override FileSystemInfo CreateObject(SearchResult result) { bool isFile = FileSystemEnumerableHelpers.IsFile(result.FindData); bool isDir = FileSystemEnumerableHelpers.IsDir(result.FindData); if (isDir) { String name = result.FullPath; String permissionName = name + "\\."; #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, permissionName); state.EnsureState(); #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, permissionName, false, false); #endif DirectoryInfo di = new DirectoryInfo(name, false); di.InitializeFrom(result.FindData); return(di); } else { Contract.Assert(isFile); String name = result.FullPath; #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name); state.EnsureState(); #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, name, false, false); #endif FileInfo fi = new FileInfo(name, false); fi.InitializeFrom(result.FindData); return(fi); } }
public static void CreateLogFolder() { try { string subPath = System.Configuration.ConfigurationManager.AppSettings["LogFilePath"].ToString() + "logs"; PermissionSet permissionSet = new PermissionSet(PermissionState.None); FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, subPath); permissionSet.AddPermission(writePermission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { if (!Directory.Exists(subPath)) { Directory.CreateDirectory(subPath); } } } catch (Exception ex) { smartOfficeMessageBox.ShowMsg(ex.Message.ToString()); } }
private UriSectionData GetSectionData() { // Assert read permission for only this file. new FileIOPermission(FileIOPermissionAccess.Read, configFilePath).Assert(); try { if (File.Exists(configFilePath)) { using (FileStream configFile = new FileStream(configFilePath, FileMode.Open, FileAccess.Read)) { XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreWhitespace = true; settings.IgnoreProcessingInstructions = true; using (reader = XmlReader.Create(configFile, settings)) { if (ReadConfiguration()) { return(sectionData); } } } } } catch (Exception) { // In this case we really want to catch all exceptions: Uri never threw, therefore we can't // start throwing exceptions now when reading the configuration. } finally { FileIOPermission.RevertAssert(); } return(null); }
private static string GetFileIOPermission(FileIOPermission ep) { if (ep.IsUnrestricted()) { return(" FileIOPermission - Unrestricted\\l"); } StringBuilder sb = new StringBuilder(" FileIOPermission\\l"); /* string[] list = ep.GetPathList (FileIOPermissionAccess.PathDiscovery); * if ((list != null) && (list.Length > 0)) { * sb.AppendFormat (" PathDiscovery: {0}\\l", s); * } * s = ep.GetPathList (FileIOPermissionAccess.Read); * if ((s != null) && (s.Length > 0)) * sb.AppendFormat (" Read: {0}\\l", s); * s = ep.GetPathList (FileIOPermissionAccess.Write); * if ((s != null) && (s.Length > 0)) * sb.AppendFormat (" Write: {0}\\l", s); * s = ep.GetPathList (FileIOPermissionAccess.Append); * if ((s != null) && (s.Length > 0)) * sb.AppendFormat (" Append: {0}\\l", s);*/ return(sb.ToString()); }
// Add file permission to restrict write access to all files // on the local machine. private static void addPolicy(ref FirstMatchCodeGroup codeGroup) { // Set the PolicyStatement property to a policy with read access to // the root directory on drive C. //<Snippet6> FileIOPermission rootFilePermissions = new FileIOPermission(PermissionState.None); rootFilePermissions.AllLocalFiles = FileIOPermissionAccess.Read; rootFilePermissions.SetPathList(FileIOPermissionAccess.Read, "C:\\"); NamedPermissionSet namedPermissions = new NamedPermissionSet("RootPermissions"); namedPermissions.AddPermission(rootFilePermissions); // Create a PolicyStatement with exclusive rights to the policy. PolicyStatement policy = new PolicyStatement( namedPermissions, PolicyStatementAttribute.Exclusive); codeGroup.PolicyStatement = policy; //</Snippet6> }
// Create a FirstMatchCodeGroup with an exclusive policy and membership // condition. private static FirstMatchCodeGroup constructDefaultGroup() { // Construct a new FirstMatchCodeGroup with Read, Write, Append // and PathDiscovery access. // Create read access permission to the root directory on drive C. FileIOPermission rootFilePermissions = new FileIOPermission(PermissionState.None); rootFilePermissions.AllLocalFiles = FileIOPermissionAccess.Read; rootFilePermissions.SetPathList(FileIOPermissionAccess.Read, "C:\\"); // Add a permission to a named permission set. NamedPermissionSet namedPermissions = new NamedPermissionSet("RootPermissions"); namedPermissions.AddPermission(rootFilePermissions); // Create a PolicyStatement with exclusive rights to the policy. PolicyStatement policy = new PolicyStatement( namedPermissions, PolicyStatementAttribute.Exclusive); // Create a FirstMatchCodeGroup with a membership condition that // matches all code, and an exclusive policy. FirstMatchCodeGroup codeGroup = new FirstMatchCodeGroup( new AllMembershipCondition(), policy); // Set the name of the first match code group. codeGroup.Name = "TempCodeGroup"; // Set the description of the first match code group. codeGroup.Description = "Temp folder permissions group"; return(codeGroup); }
public UserControl1() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // The OpenFileDialog box should not require any special permissions. OpenFileDialog fileDialog = new OpenFileDialog(); if (fileDialog.ShowDialog() == DialogResult.OK) { // Reading the name of the selected file from the OpenFileDialog box // and reading the file requires FileIOPermission. The user control should // have this permission granted through its code group; the Web page that calls the // control should not have this permission. The Assert command prevents a stack walk // that would fail because the caller does not have the required FileIOPermission. // The use of Assert can open up security vulnerabilities if used incorrectly or // inappropriately. Therefore, it should be used with great caution. // The Assert command should be followed by a RevertAssert as soon as the file operation // is completed. new FileIOPermission(PermissionState.Unrestricted).Assert(); textBox1.Text = fileDialog.FileName; // Display the contents of the file in the text box. FileStream fsIn = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read, FileShare.Read); StreamReader sr = new StreamReader(fsIn); // Process every line in the file for (String Line = sr.ReadLine(); Line != null; Line = sr.ReadLine()) { listBox1.Items.Add(Line); } // It is very important to call RevertAssert to restore the stack walk for // file operations. FileIOPermission.RevertAssert(); } }
public static bool CheckWritePermission(string physicalTargetPath, string virtualTargetPath) { FileIOPermission f = new FileIOPermission(FileIOPermissionAccess.Write, physicalTargetPath); try { f.Demand(); return true; } catch (SecurityException) { return false; } }
private bool hasWriteAccessToFolder(string folderPath) { try { var permission = new FileIOPermission(FileIOPermissionAccess.Write, folderPath); var permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(permission); if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet)) { return true; } else { return false; } } catch (UnauthorizedAccessException) { return false; } }
// MembershipProvider Methods public override void Initialize(string name, NameValueCollection config) { // Verify that config isn't null if (config == null) { throw new ArgumentNullException("config"); } // Assign the provider a default name if it doesn't have one if (String.IsNullOrEmpty(name)) { name = "XmlMembershipProvider"; } // Add a default "description" attribute to config if the // attribute doesn’t exist or is empty if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "XML membership provider"); } // Call the base class's Initialize method base.Initialize(name, config); // Initialize xmlFileName and make sure the path is app-relative string path = config["xmlFileName"]; if (String.IsNullOrEmpty(path)) { path = "~/App_Data/Users.xml"; } if (!VirtualPathUtility.IsAppRelative(path)) { throw new ArgumentException(Resources.Common.XMLFileNameMustBeAppRelative); } string fullyQualifiedPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash(HttpRuntime.AppDomainAppVirtualPath), path); this.xmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath); config.Remove("xmlFileName"); // Make sure we have permission to read the XML data source and // throw an exception if we don't FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, this.xmlFileName); permission.Demand(); // Throw an exception if unrecognized attributes remain if (config.Count > 0) { string attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) { throw new ProviderException(Resources.Common.UnrecognizedAttribute + attr); } } }
internal IsolatedStorageFileEnumerator(IsolatedStorageScope scope) { m_Scope = scope; m_fiop = IsolatedStorageFile.GetGlobalFileIOPerm(scope); m_rootDir = IsolatedStorageFile.GetRootDir(scope); m_fileEnum = new TwoLevelFileEnumerator(m_rootDir); Reset(); }
private void Initialize() { string fullyQualifiedPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (HttpRuntime.AppDomainAppVirtualPath), this.xmlFileName); this.xmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath); // Make sure we have permission to read the XML data source and throw an exception if we don't FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, this.xmlFileName); permission.Demand(); ReadDataStore(); }
public override void Initialize(string name, NameValueCollection config) { // Verify that config isn't null if (config == null) throw new ArgumentNullException("config"); // Assign the provider a default name if it doesn't have one if (String.IsNullOrEmpty(name)) name = "TextFileProfileProvider"; // Add a default "description" attribute to config if the // attribute doesn't exist or is empty if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Text file profile provider"); } // Call the base class's Initialize method base.Initialize(name, config); // Throw an exception if unrecognized attributes remain if (config.Count > 0) { string attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) throw new ProviderException("Unrecognized attribute: " + attr); } // Make sure we can read and write files // in the Profile_Data directory FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, AbsoluteProfileFilePath); permission.Demand(); }
public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (String.IsNullOrEmpty(name)) name = "XmlMembershipProvider"; if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "XML membership provider"); } base.Initialize(name, config); // Initialize _XmlFileName and make sure the path // is app-relative string path = config["xmlFileName"]; if (String.IsNullOrEmpty(path)) path = "~/admin/Users.xml"; if (!VirtualPathUtility.IsAppRelative(path)) throw new ArgumentException ("xmlFileName must be app-relative"); string fullyQualifiedPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (HttpRuntime.AppDomainAppVirtualPath), path); _XmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath); config.Remove("xmlFileName"); // Make sure we have permission to read the XML data source and // throw an exception if we don't FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, _XmlFileName); permission.Demand(); // Throw an exception if unrecognized attributes remain if (config.Count > 0) { string attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) throw new ProviderException("Unrecognized attribute: " + attr); } }
private void TestFileIOPermisssion() { FileIOPermission perm = new FileIOPermission(PermissionState.Unrestricted); perm.Deny(); RegexCompilationInfo[] compiles; AssemblyName asmName; compiles = new RegexCompilationInfo[1]; compiles[0] = new RegexCompilationInfo(@"[a-z]+\d+", RegexOptions.None, "RegexPatOne", "RegexPatterns", true); asmName = new AssemblyName(); asmName.Name = "RegexPatAsm3"; Regex.CompileToAssembly(compiles, asmName); }
/// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="config"></param> public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (String.IsNullOrEmpty(name)) name = "XmlMembershipProvider"; if (Type.GetType("Mono.Runtime") != null) { // Mono dies with a "Unrecognized attribute: description" if a description is part of the config. if (!string.IsNullOrEmpty(config["description"])) { config.Remove("description"); } } else { if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "XML membership provider"); } } base.Initialize(name, config); // Initialize _XmlFileName and make sure the path // is app-relative string path = config["xmlFileName"]; if (String.IsNullOrEmpty(path)) { path = DataIO.UsersLocation; } //path = BlogSettings.Instance.StorageLocation + "users.xml"; if (!VirtualPathUtility.IsAppRelative(path)) throw new ArgumentException ("xmlFileName must be app-relative"); string fullyQualifiedPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (HttpRuntime.AppDomainAppVirtualPath), path); _XmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath); config.Remove("xmlFileName"); // Make sure we have permission to read the XML data source and // throw an exception if we don't FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, _XmlFileName); permission.Demand(); //Password Format if (config["passwordFormat"] == null) { config["passwordFormat"] = "Hashed"; passwordFormat = MembershipPasswordFormat.Hashed; } else if (String.Compare(config["passwordFormat"], "clear", true) == 0) { passwordFormat = MembershipPasswordFormat.Clear; } else { passwordFormat = MembershipPasswordFormat.Hashed; } config.Remove("passwordFormat"); // Throw an exception if unrecognized attributes remain if (config.Count > 0) { string attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) throw new ProviderException("Unrecognized attribute: " + attr); } }