IsolatedStorageFile.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. //
  2. // System.IO.IsolatedStorage.IsolatedStorageFile
  3. //
  4. // Authors
  5. // Jonathan Pryor ([email protected])
  6. // Sebastien Pouliot <[email protected]>
  7. //
  8. // (C) 2003 Jonathan Pryor
  9. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. #if !MOONLIGHT
  31. using System.Collections;
  32. using System.Reflection;
  33. using System.Runtime.InteropServices;
  34. using System.Runtime.Serialization.Formatters.Binary;
  35. using System.Security;
  36. using System.Security.Cryptography;
  37. using System.Security.Permissions;
  38. using System.Security.Policy;
  39. using System.Text;
  40. using System.Threading;
  41. using Mono.Security.Cryptography;
  42. namespace System.IO.IsolatedStorage {
  43. // This is a terribly named class. It doesn't actually represent a file as
  44. // much as a directory
  45. [ComVisible (true)]
  46. // FIXME: Further limit the assertion when imperative Assert is implemented
  47. [FileIOPermission (SecurityAction.Assert, Unrestricted = true)]
  48. public sealed class IsolatedStorageFile : IsolatedStorage, IDisposable {
  49. private bool _resolved;
  50. private ulong _maxSize;
  51. private Evidence _fullEvidences;
  52. private static Mutex mutex = new Mutex ();
  53. #if NET_4_0
  54. private bool closed;
  55. private bool disposed;
  56. #endif
  57. public static IEnumerator GetEnumerator (IsolatedStorageScope scope)
  58. {
  59. Demand (scope);
  60. switch (scope) {
  61. case IsolatedStorageScope.User:
  62. case IsolatedStorageScope.User | IsolatedStorageScope.Roaming:
  63. case IsolatedStorageScope.Machine:
  64. break;
  65. default:
  66. string msg = Locale.GetText ("Invalid scope, only User, User|Roaming and Machine are valid");
  67. throw new ArgumentException (msg);
  68. }
  69. return new IsolatedStorageFileEnumerator (scope, GetIsolatedStorageRoot (scope));
  70. }
  71. public static IsolatedStorageFile GetStore (IsolatedStorageScope scope,
  72. Evidence domainEvidence, Type domainEvidenceType,
  73. Evidence assemblyEvidence, Type assemblyEvidenceType)
  74. {
  75. Demand (scope);
  76. bool domain = ((scope & IsolatedStorageScope.Domain) != 0);
  77. if (domain && (domainEvidence == null))
  78. throw new ArgumentNullException ("domainEvidence");
  79. bool assembly = ((scope & IsolatedStorageScope.Assembly) != 0);
  80. if (assembly && (assemblyEvidence == null))
  81. throw new ArgumentNullException ("assemblyEvidence");
  82. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  83. if (domain) {
  84. if (domainEvidenceType == null) {
  85. storageFile._domainIdentity = GetDomainIdentityFromEvidence (domainEvidence);
  86. } else {
  87. storageFile._domainIdentity = GetTypeFromEvidence (domainEvidence, domainEvidenceType);
  88. }
  89. if (storageFile._domainIdentity == null)
  90. throw new IsolatedStorageException (Locale.GetText ("Couldn't find domain identity."));
  91. }
  92. if (assembly) {
  93. if (assemblyEvidenceType == null) {
  94. storageFile._assemblyIdentity = GetAssemblyIdentityFromEvidence (assemblyEvidence);
  95. } else {
  96. storageFile._assemblyIdentity = GetTypeFromEvidence (assemblyEvidence, assemblyEvidenceType);
  97. }
  98. if (storageFile._assemblyIdentity == null)
  99. throw new IsolatedStorageException (Locale.GetText ("Couldn't find assembly identity."));
  100. }
  101. storageFile.PostInit ();
  102. return storageFile;
  103. }
  104. public static IsolatedStorageFile GetStore (IsolatedStorageScope scope, object domainIdentity, object assemblyIdentity)
  105. {
  106. Demand (scope);
  107. if (((scope & IsolatedStorageScope.Domain) != 0) && (domainIdentity == null))
  108. throw new ArgumentNullException ("domainIdentity");
  109. bool assembly = ((scope & IsolatedStorageScope.Assembly) != 0);
  110. if (assembly && (assemblyIdentity == null))
  111. throw new ArgumentNullException ("assemblyIdentity");
  112. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  113. if (assembly)
  114. storageFile._fullEvidences = Assembly.GetCallingAssembly ().UnprotectedGetEvidence ();
  115. storageFile._domainIdentity = domainIdentity;
  116. storageFile._assemblyIdentity = assemblyIdentity;
  117. storageFile.PostInit ();
  118. return storageFile;
  119. }
  120. public static IsolatedStorageFile GetStore (IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType)
  121. {
  122. Demand (scope);
  123. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  124. if ((scope & IsolatedStorageScope.Domain) != 0) {
  125. if (domainEvidenceType == null)
  126. domainEvidenceType = typeof (Url);
  127. storageFile._domainIdentity = GetTypeFromEvidence (AppDomain.CurrentDomain.Evidence, domainEvidenceType);
  128. }
  129. if ((scope & IsolatedStorageScope.Assembly) != 0) {
  130. Evidence e = Assembly.GetCallingAssembly ().UnprotectedGetEvidence ();
  131. storageFile._fullEvidences = e;
  132. if ((scope & IsolatedStorageScope.Domain) != 0) {
  133. if (assemblyEvidenceType == null)
  134. assemblyEvidenceType = typeof (Url);
  135. storageFile._assemblyIdentity = GetTypeFromEvidence (e, assemblyEvidenceType);
  136. } else {
  137. storageFile._assemblyIdentity = GetAssemblyIdentityFromEvidence (e);
  138. }
  139. }
  140. storageFile.PostInit ();
  141. return storageFile;
  142. }
  143. public static IsolatedStorageFile GetStore (IsolatedStorageScope scope, object applicationIdentity)
  144. {
  145. Demand (scope);
  146. if (applicationIdentity == null)
  147. throw new ArgumentNullException ("applicationIdentity");
  148. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  149. storageFile._applicationIdentity = applicationIdentity;
  150. storageFile._fullEvidences = Assembly.GetCallingAssembly ().UnprotectedGetEvidence ();
  151. storageFile.PostInit ();
  152. return storageFile;
  153. }
  154. public static IsolatedStorageFile GetStore (IsolatedStorageScope scope, Type applicationEvidenceType)
  155. {
  156. Demand (scope);
  157. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  158. storageFile.InitStore (scope, applicationEvidenceType);
  159. storageFile._fullEvidences = Assembly.GetCallingAssembly ().UnprotectedGetEvidence ();
  160. storageFile.PostInit ();
  161. return storageFile;
  162. }
  163. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.ApplicationIsolationByMachine)]
  164. public static IsolatedStorageFile GetMachineStoreForApplication ()
  165. {
  166. IsolatedStorageScope scope = IsolatedStorageScope.Machine | IsolatedStorageScope.Application;
  167. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  168. storageFile.InitStore (scope, null);
  169. storageFile._fullEvidences = Assembly.GetCallingAssembly ().UnprotectedGetEvidence ();
  170. storageFile.PostInit ();
  171. return storageFile;
  172. }
  173. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByMachine)]
  174. public static IsolatedStorageFile GetMachineStoreForAssembly ()
  175. {
  176. IsolatedStorageScope scope = IsolatedStorageScope.Machine | IsolatedStorageScope.Assembly;
  177. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  178. Evidence e = Assembly.GetCallingAssembly ().UnprotectedGetEvidence ();
  179. storageFile._fullEvidences = e;
  180. storageFile._assemblyIdentity = GetAssemblyIdentityFromEvidence (e);
  181. storageFile.PostInit ();
  182. return storageFile;
  183. }
  184. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.DomainIsolationByMachine)]
  185. public static IsolatedStorageFile GetMachineStoreForDomain ()
  186. {
  187. IsolatedStorageScope scope = IsolatedStorageScope.Machine | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly;
  188. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  189. storageFile._domainIdentity = GetDomainIdentityFromEvidence (AppDomain.CurrentDomain.Evidence);
  190. Evidence e = Assembly.GetCallingAssembly ().UnprotectedGetEvidence ();
  191. storageFile._fullEvidences = e;
  192. storageFile._assemblyIdentity = GetAssemblyIdentityFromEvidence (e);
  193. storageFile.PostInit ();
  194. return storageFile;
  195. }
  196. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.ApplicationIsolationByUser)]
  197. public static IsolatedStorageFile GetUserStoreForApplication ()
  198. {
  199. IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Application;
  200. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  201. storageFile.InitStore (scope, null);
  202. storageFile._fullEvidences = Assembly.GetCallingAssembly ().UnprotectedGetEvidence ();
  203. storageFile.PostInit ();
  204. return storageFile;
  205. }
  206. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser)]
  207. public static IsolatedStorageFile GetUserStoreForAssembly ()
  208. {
  209. IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;
  210. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  211. Evidence e = Assembly.GetCallingAssembly ().UnprotectedGetEvidence ();
  212. storageFile._fullEvidences = e;
  213. storageFile._assemblyIdentity = GetAssemblyIdentityFromEvidence (e);
  214. storageFile.PostInit ();
  215. return storageFile;
  216. }
  217. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.DomainIsolationByUser)]
  218. public static IsolatedStorageFile GetUserStoreForDomain ()
  219. {
  220. IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly;
  221. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  222. storageFile._domainIdentity = GetDomainIdentityFromEvidence (AppDomain.CurrentDomain.Evidence);
  223. Evidence e = Assembly.GetCallingAssembly ().UnprotectedGetEvidence ();
  224. storageFile._fullEvidences = e;
  225. storageFile._assemblyIdentity = GetAssemblyIdentityFromEvidence (e);
  226. storageFile.PostInit ();
  227. return storageFile;
  228. }
  229. public static void Remove (IsolatedStorageScope scope)
  230. {
  231. string dir = GetIsolatedStorageRoot (scope);
  232. Directory.Delete (dir, true);
  233. }
  234. // internal static stuff
  235. // Security Note: We're using InternalGetFolderPath because
  236. // IsolatedStorage must be able to work even if we do not have
  237. // FileIOPermission's PathDiscovery permissions
  238. internal static string GetIsolatedStorageRoot (IsolatedStorageScope scope)
  239. {
  240. // IsolatedStorageScope mixes several flags into one.
  241. // This first level deals with the root directory - it
  242. // is decided based on User, User+Roaming or Machine
  243. string root = null;
  244. if ((scope & IsolatedStorageScope.User) != 0) {
  245. if ((scope & IsolatedStorageScope.Roaming) != 0) {
  246. root = Environment.InternalGetFolderPath (Environment.SpecialFolder.LocalApplicationData);
  247. } else {
  248. root = Environment.InternalGetFolderPath (Environment.SpecialFolder.ApplicationData);
  249. }
  250. } else if ((scope & IsolatedStorageScope.Machine) != 0) {
  251. root = Environment.InternalGetFolderPath (Environment.SpecialFolder.CommonApplicationData);
  252. }
  253. if (root == null) {
  254. string msg = Locale.GetText ("Couldn't access storage location for '{0}'.");
  255. throw new IsolatedStorageException (String.Format (msg, scope));
  256. }
  257. return Path.Combine (root, ".isolated-storage");
  258. }
  259. private static void Demand (IsolatedStorageScope scope)
  260. {
  261. if (SecurityManager.SecurityEnabled) {
  262. IsolatedStorageFilePermission isfp = new IsolatedStorageFilePermission (PermissionState.None);
  263. isfp.UsageAllowed = ScopeToContainment (scope);
  264. isfp.Demand ();
  265. }
  266. }
  267. private static IsolatedStorageContainment ScopeToContainment (IsolatedStorageScope scope)
  268. {
  269. switch (scope) {
  270. case IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly | IsolatedStorageScope.User:
  271. return IsolatedStorageContainment.DomainIsolationByUser;
  272. case IsolatedStorageScope.Assembly | IsolatedStorageScope.User:
  273. return IsolatedStorageContainment.AssemblyIsolationByUser;
  274. case IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly | IsolatedStorageScope.User | IsolatedStorageScope.Roaming:
  275. return IsolatedStorageContainment.DomainIsolationByRoamingUser;
  276. case IsolatedStorageScope.Assembly | IsolatedStorageScope.User | IsolatedStorageScope.Roaming:
  277. return IsolatedStorageContainment.AssemblyIsolationByRoamingUser;
  278. case IsolatedStorageScope.Application | IsolatedStorageScope.User:
  279. return IsolatedStorageContainment.ApplicationIsolationByUser;
  280. case IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly | IsolatedStorageScope.Machine:
  281. return IsolatedStorageContainment.DomainIsolationByMachine;
  282. case IsolatedStorageScope.Assembly | IsolatedStorageScope.Machine:
  283. return IsolatedStorageContainment.AssemblyIsolationByMachine;
  284. case IsolatedStorageScope.Application | IsolatedStorageScope.Machine:
  285. return IsolatedStorageContainment.ApplicationIsolationByMachine;
  286. case IsolatedStorageScope.Application | IsolatedStorageScope.User | IsolatedStorageScope.Roaming:
  287. return IsolatedStorageContainment.ApplicationIsolationByRoamingUser;
  288. default:
  289. // unknown ?!?! then ask for maximum (unrestricted)
  290. return IsolatedStorageContainment.UnrestrictedIsolatedStorage;
  291. }
  292. }
  293. internal static ulong GetDirectorySize (DirectoryInfo di)
  294. {
  295. ulong size = 0;
  296. foreach (FileInfo fi in di.GetFiles ())
  297. size += (ulong) fi.Length;
  298. foreach (DirectoryInfo d in di.GetDirectories ())
  299. size += GetDirectorySize (d);
  300. return size;
  301. }
  302. // non-static stuff
  303. private DirectoryInfo directory;
  304. private IsolatedStorageFile (IsolatedStorageScope scope)
  305. {
  306. storage_scope = scope;
  307. }
  308. internal IsolatedStorageFile (IsolatedStorageScope scope, string location)
  309. {
  310. storage_scope = scope;
  311. directory = new DirectoryInfo (location);
  312. if (!directory.Exists) {
  313. string msg = Locale.GetText ("Invalid storage.");
  314. throw new IsolatedStorageException (msg);
  315. }
  316. // load the identities
  317. }
  318. ~IsolatedStorageFile ()
  319. {
  320. }
  321. private void PostInit ()
  322. {
  323. string root = GetIsolatedStorageRoot (Scope);
  324. string dir = null;
  325. if (_applicationIdentity != null) {
  326. dir = String.Format ("a{0}{1}", SeparatorInternal, GetNameFromIdentity (_applicationIdentity));
  327. } else if (_domainIdentity != null) {
  328. dir = String.Format ("d{0}{1}{0}{2}", SeparatorInternal,
  329. GetNameFromIdentity (_domainIdentity), GetNameFromIdentity (_assemblyIdentity));
  330. } else if (_assemblyIdentity != null) {
  331. dir = String.Format ("d{0}none{0}{1}", SeparatorInternal, GetNameFromIdentity (_assemblyIdentity));
  332. } else {
  333. throw new IsolatedStorageException (Locale.GetText ("No code identity available."));
  334. }
  335. root = Path.Combine (root, dir);
  336. // identities have been selected
  337. directory = new DirectoryInfo (root);
  338. if (!directory.Exists) {
  339. try {
  340. directory.Create ();
  341. SaveIdentities (root);
  342. }
  343. catch (IOException) {
  344. }
  345. }
  346. }
  347. [CLSCompliant(false)]
  348. #if NET_4_0
  349. [Obsolete]
  350. #endif
  351. public override ulong CurrentSize {
  352. get { return GetDirectorySize (directory); }
  353. }
  354. [CLSCompliant(false)]
  355. #if NET_4_0
  356. [Obsolete]
  357. #endif
  358. public override ulong MaximumSize {
  359. // return an ulong but default is signed long
  360. get {
  361. if (!SecurityManager.SecurityEnabled)
  362. return Int64.MaxValue;
  363. if (_resolved)
  364. return _maxSize;
  365. Evidence e = null;
  366. if (_fullEvidences != null) {
  367. // if possible use the complete evidences we had
  368. // for computing the X identity
  369. e = _fullEvidences;
  370. } else {
  371. e = new Evidence ();
  372. // otherwise use what was provided
  373. if (_assemblyIdentity != null)
  374. e.AddHost (_assemblyIdentity);
  375. }
  376. if (e.Count < 1) {
  377. throw new InvalidOperationException (
  378. Locale.GetText ("Couldn't get the quota from the available evidences."));
  379. }
  380. PermissionSet denied = null;
  381. PermissionSet ps = SecurityManager.ResolvePolicy (e, null, null, null, out denied);
  382. IsolatedStoragePermission isp = GetPermission (ps);
  383. if (isp == null) {
  384. if (ps.IsUnrestricted ()) {
  385. _maxSize = Int64.MaxValue; /* default value */
  386. } else {
  387. throw new InvalidOperationException (
  388. Locale.GetText ("No quota from the available evidences."));
  389. }
  390. } else {
  391. _maxSize = (ulong) isp.UserQuota;
  392. }
  393. _resolved = true;
  394. return _maxSize;
  395. }
  396. }
  397. internal string Root {
  398. get { return directory.FullName; }
  399. }
  400. #if NET_4_0
  401. [ComVisible (false)]
  402. public override long AvailableFreeSpace {
  403. get {
  404. CheckOpen ();
  405. // See the notes for 'Quota'
  406. return Int64.MaxValue;
  407. }
  408. }
  409. [ComVisible (false)]
  410. public override long Quota {
  411. get {
  412. CheckOpen ();
  413. // Since we don't fully support CAS, we are likely
  414. // going to return Int64.MaxValue always, but we return
  415. // MaximumSize just in case.
  416. return (long)MaximumSize;
  417. }
  418. }
  419. [ComVisible (false)]
  420. public override long UsedSize {
  421. get {
  422. CheckOpen ();
  423. return (long)GetDirectorySize (directory);
  424. }
  425. }
  426. [ComVisible (false)]
  427. public static bool IsEnabled {
  428. get {
  429. return true;
  430. }
  431. }
  432. internal bool IsClosed {
  433. get {
  434. return closed;
  435. }
  436. }
  437. internal bool IsDisposed {
  438. get {
  439. return disposed;
  440. }
  441. }
  442. #endif
  443. // methods
  444. public void Close ()
  445. {
  446. #if NET_4_0
  447. closed = true;
  448. #endif
  449. }
  450. public void CreateDirectory (string dir)
  451. {
  452. if (dir == null)
  453. throw new ArgumentNullException ("dir");
  454. if (dir.IndexOfAny (Path.PathSeparatorChars) < 0) {
  455. if (directory.GetFiles (dir).Length > 0)
  456. throw new IOException (Locale.GetText ("Directory name already exists as a file."));
  457. directory.CreateSubdirectory (dir);
  458. } else {
  459. string[] dirs = dir.Split (Path.PathSeparatorChars);
  460. DirectoryInfo dinfo = directory;
  461. for (int i = 0; i < dirs.Length; i++) {
  462. if (dinfo.GetFiles (dirs [i]).Length > 0)
  463. throw new IOException (Locale.GetText (
  464. "Part of the directory name already exists as a file."));
  465. dinfo = dinfo.CreateSubdirectory (dirs [i]);
  466. }
  467. }
  468. }
  469. #if NET_4_0
  470. [ComVisible (false)]
  471. public void CopyFile (string sourceFileName, string destinationFileName)
  472. {
  473. CopyFile (sourceFileName, destinationFileName, false);
  474. }
  475. [ComVisible (false)]
  476. public void CopyFile (string sourceFileName, string destinationFileName, bool overwrite)
  477. {
  478. if (sourceFileName == null)
  479. throw new ArgumentNullException ("sourceFileName");
  480. if (destinationFileName == null)
  481. throw new ArgumentNullException ("destinationFileName");
  482. if (sourceFileName.Trim ().Length == 0)
  483. throw new ArgumentException ("An empty file name is not valid.", "sourceFileName");
  484. if (destinationFileName.Trim ().Length == 0)
  485. throw new ArgumentException ("An empty file name is not valid.", "destinationFileName");
  486. CheckOpen ();
  487. string source_full_path = Path.Combine (directory.FullName, sourceFileName);
  488. string dest_full_path = Path.Combine (directory.FullName, destinationFileName);
  489. // These excs can be thrown from File.Copy, but we can try to detect them from here.
  490. if (!Directory.Exists (Path.GetDirectoryName (source_full_path)))
  491. throw new DirectoryNotFoundException ("Could not find a part of path '" + sourceFileName + "'.");
  492. if (!File.Exists (source_full_path))
  493. throw new FileNotFoundException ("Could not find a part of path '" + sourceFileName + "'.");
  494. if (File.Exists (dest_full_path) && !overwrite)
  495. throw new IsolatedStorageException ("Operation not allowed.");
  496. try {
  497. File.Copy (source_full_path, dest_full_path, overwrite);
  498. } catch (IOException) {
  499. throw new IsolatedStorageException ("Operation not allowed.");
  500. }
  501. }
  502. [ComVisible (false)]
  503. public IsolatedStorageFileStream CreateFile (string path)
  504. {
  505. return new IsolatedStorageFileStream (path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, this);
  506. }
  507. #endif
  508. public void DeleteDirectory (string dir)
  509. {
  510. try {
  511. DirectoryInfo subdir = directory.CreateSubdirectory (dir);
  512. subdir.Delete ();
  513. }
  514. catch {
  515. // hide the real exception to avoid leaking the full path
  516. throw new IsolatedStorageException (Locale.GetText ("Could not delete directory '{0}'", dir));
  517. }
  518. }
  519. public void DeleteFile (string file)
  520. {
  521. File.Delete (Path.Combine (directory.FullName, file));
  522. }
  523. public void Dispose ()
  524. {
  525. #if NET_4_0
  526. // Dispose may be calling Close, but we are not sure
  527. disposed = true;
  528. #endif
  529. // nothing to dispose, anyway we want to please the tools
  530. GC.SuppressFinalize (this);
  531. }
  532. #if NET_4_0
  533. [ComVisible (false)]
  534. public bool DirectoryExists (string path)
  535. {
  536. if (path == null)
  537. throw new ArgumentNullException ("path");
  538. CheckOpen ();
  539. return Directory.Exists (Path.Combine (directory.FullName, path));
  540. }
  541. [ComVisible (false)]
  542. public bool FileExists (string path)
  543. {
  544. if (path == null)
  545. throw new ArgumentNullException ("path");
  546. CheckOpen ();
  547. return File.Exists (Path.Combine (directory.FullName, path));
  548. }
  549. [ComVisible (false)]
  550. public DateTimeOffset GetCreationTime (string path)
  551. {
  552. if (path == null)
  553. throw new ArgumentNullException ("path");
  554. if (path.Trim ().Length == 0)
  555. throw new ArgumentException ("An empty path is not valid.");
  556. CheckOpen ();
  557. string full_path = Path.Combine (directory.FullName, path);
  558. if (File.Exists (full_path))
  559. return File.GetCreationTime (full_path);
  560. return Directory.GetCreationTime (full_path);
  561. }
  562. [ComVisible (false)]
  563. public DateTimeOffset GetLastAccessTime (string path)
  564. {
  565. if (path == null)
  566. throw new ArgumentNullException ("path");
  567. if (path.Trim ().Length == 0)
  568. throw new ArgumentException ("An empty path is not valid.");
  569. CheckOpen ();
  570. string full_path = Path.Combine (directory.FullName, path);
  571. if (File.Exists (full_path))
  572. return File.GetLastAccessTime (full_path);
  573. return Directory.GetLastAccessTime (full_path);
  574. }
  575. [ComVisible (false)]
  576. public DateTimeOffset GetLastWriteTime (string path)
  577. {
  578. if (path == null)
  579. throw new ArgumentNullException ("path");
  580. if (path.Trim ().Length == 0)
  581. throw new ArgumentException ("An empty path is not valid.");
  582. CheckOpen ();
  583. string full_path = Path.Combine (directory.FullName, path);
  584. if (File.Exists (full_path))
  585. return File.GetLastWriteTime (full_path);
  586. return Directory.GetLastWriteTime (full_path);
  587. }
  588. #endif
  589. public string[] GetDirectoryNames (string searchPattern)
  590. {
  591. if (searchPattern == null)
  592. throw new ArgumentNullException ("searchPattern");
  593. // note: IsolatedStorageFile accept a "dir/file" pattern which is not allowed by DirectoryInfo
  594. // so we need to split them to get the right results
  595. string path = Path.GetDirectoryName (searchPattern);
  596. string pattern = Path.GetFileName (searchPattern);
  597. DirectoryInfo[] adi = null;
  598. if (path == null || path.Length == 0) {
  599. adi = directory.GetDirectories (searchPattern);
  600. } else {
  601. DirectoryInfo[] subdirs = directory.GetDirectories (path);
  602. // we're looking for a single result, identical to path (no pattern here)
  603. // we're also looking for something under the current path (not outside isolated storage)
  604. if ((subdirs.Length == 1) && (subdirs [0].Name == path) && (subdirs [0].FullName.IndexOf (directory.FullName) >= 0)) {
  605. adi = subdirs [0].GetDirectories (pattern);
  606. } else {
  607. // CAS, even in FullTrust, normally enforce IsolatedStorage
  608. throw new SecurityException ();
  609. }
  610. }
  611. return GetNames (adi);
  612. }
  613. #if NET_4_0
  614. [ComVisible (false)]
  615. public string [] GetDirectoryNames ()
  616. {
  617. return GetDirectoryNames ("*");
  618. }
  619. #endif
  620. private string[] GetNames (FileSystemInfo[] afsi)
  621. {
  622. string[] r = new string[afsi.Length];
  623. for (int i = 0; i != afsi.Length; ++i)
  624. r[i] = afsi[i].Name;
  625. return r;
  626. }
  627. public string[] GetFileNames (string searchPattern)
  628. {
  629. if (searchPattern == null)
  630. throw new ArgumentNullException ("searchPattern");
  631. // note: IsolatedStorageFile accept a "dir/file" pattern which is not allowed by DirectoryInfo
  632. // so we need to split them to get the right results
  633. string path = Path.GetDirectoryName (searchPattern);
  634. string pattern = Path.GetFileName (searchPattern);
  635. FileInfo[] afi = null;
  636. if (path == null || path.Length == 0) {
  637. afi = directory.GetFiles (searchPattern);
  638. } else {
  639. DirectoryInfo[] subdirs = directory.GetDirectories (path);
  640. // we're looking for a single result, identical to path (no pattern here)
  641. // we're also looking for something under the current path (not outside isolated storage)
  642. if ((subdirs.Length == 1) && (subdirs [0].Name == path) && (subdirs [0].FullName.IndexOf (directory.FullName) >= 0)) {
  643. afi = subdirs [0].GetFiles (pattern);
  644. } else {
  645. // CAS, even in FullTrust, normally enforce IsolatedStorage
  646. throw new SecurityException ();
  647. }
  648. }
  649. return GetNames (afi);
  650. }
  651. #if NET_4_0
  652. [ComVisible (false)]
  653. public string [] GetFileNames ()
  654. {
  655. return GetFileNames ("*");
  656. }
  657. [ComVisible (false)]
  658. public override bool IncreaseQuotaTo (long newQuotaSize)
  659. {
  660. if (newQuotaSize < Quota)
  661. throw new ArgumentException ();
  662. CheckOpen ();
  663. // .Net is supposed to be returning false, as mentioned in the docs.
  664. return false;
  665. }
  666. [ComVisible (false)]
  667. public void MoveDirectory (string sourceDirectoryName, string destinationDirectoryName)
  668. {
  669. if (sourceDirectoryName == null)
  670. throw new ArgumentNullException ("sourceDirectoryName");
  671. if (destinationDirectoryName == null)
  672. throw new ArgumentNullException ("sourceDirectoryName");
  673. CheckOpen ();
  674. Directory.Move (Path.Combine (directory.FullName, sourceDirectoryName),
  675. Path.Combine (directory.FullName, destinationDirectoryName));
  676. }
  677. [ComVisible (false)]
  678. public void MoveFile (string sourceFileName, string destinationFileName)
  679. {
  680. if (sourceFileName == null)
  681. throw new ArgumentNullException ("sourceFileName");
  682. if (destinationFileName == null)
  683. throw new ArgumentNullException ("sourceFileName");
  684. CheckOpen ();
  685. File.Move (Path.Combine (directory.FullName, sourceFileName),
  686. Path.Combine (directory.FullName, destinationFileName));
  687. }
  688. [ComVisible (false)]
  689. public IsolatedStorageFileStream OpenFile (string path, FileMode mode)
  690. {
  691. return new IsolatedStorageFileStream (path, mode, this);
  692. }
  693. [ComVisible (false)]
  694. public IsolatedStorageFileStream OpenFile (string path, FileMode mode, FileAccess access)
  695. {
  696. return new IsolatedStorageFileStream (path, mode, access, this);
  697. }
  698. [ComVisible (false)]
  699. public IsolatedStorageFileStream OpenFile (string path, FileMode mode, FileAccess access, FileShare share)
  700. {
  701. return new IsolatedStorageFileStream (path, mode, access, share, this);
  702. }
  703. #endif
  704. public override void Remove ()
  705. {
  706. directory.Delete (true);
  707. // It seems .Net is calling Close from here.
  708. Close ();
  709. }
  710. protected override IsolatedStoragePermission GetPermission (PermissionSet ps)
  711. {
  712. if (ps == null)
  713. return null;
  714. return (IsolatedStoragePermission) ps.GetPermission (typeof (IsolatedStorageFilePermission));
  715. }
  716. // internal stuff
  717. #if NET_4_0
  718. void CheckOpen ()
  719. {
  720. if (disposed)
  721. throw new ObjectDisposedException ("IsolatedStorageFile");
  722. if (closed)
  723. throw new InvalidOperationException ("Storage needs to be open for this operation.");
  724. }
  725. #endif
  726. private string GetNameFromIdentity (object identity)
  727. {
  728. // Note: Default evidences return an XML string with ToString
  729. byte[] id = Encoding.UTF8.GetBytes (identity.ToString ());
  730. SHA1 hash = SHA1.Create ();
  731. // this create an unique name for an identity - bad identities like Url
  732. // results in bad (i.e. changing) names.
  733. byte[] full = hash.ComputeHash (id, 0, id.Length);
  734. byte[] half = new byte [10];
  735. Buffer.BlockCopy (full, 0, half, 0, half.Length);
  736. return CryptoConvert.ToHex (half);
  737. }
  738. private static object GetTypeFromEvidence (Evidence e, Type t)
  739. {
  740. foreach (object o in e) {
  741. if (o.GetType () == t)
  742. return o;
  743. }
  744. return null;
  745. }
  746. internal static object GetAssemblyIdentityFromEvidence (Evidence e)
  747. {
  748. // we prefer...
  749. // a. a Publisher evidence
  750. object identity = GetTypeFromEvidence (e, typeof (Publisher));
  751. if (identity != null)
  752. return identity;
  753. // b. a StrongName evidence
  754. identity = GetTypeFromEvidence (e, typeof (StrongName));
  755. if (identity != null)
  756. return identity;
  757. // c. a Url evidence
  758. return GetTypeFromEvidence (e, typeof (Url));
  759. }
  760. internal static object GetDomainIdentityFromEvidence (Evidence e)
  761. {
  762. // we prefer...
  763. // a. a ApplicationDirectory evidence
  764. object identity = GetTypeFromEvidence (e, typeof (ApplicationDirectory));
  765. if (identity != null)
  766. return identity;
  767. // b. a Url evidence
  768. return GetTypeFromEvidence (e, typeof (Url));
  769. }
  770. [Serializable]
  771. private struct Identities {
  772. public object Application;
  773. public object Assembly;
  774. public object Domain;
  775. public Identities (object application, object assembly, object domain)
  776. {
  777. Application = application;
  778. Assembly = assembly;
  779. Domain = domain;
  780. }
  781. }
  782. /*
  783. [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)]
  784. private void LoadIdentities (string root)
  785. {
  786. if (!File.Exists (root + ".storage"))
  787. throw new IsolatedStorageException (Locale.GetText ("Missing identities."));
  788. BinaryFormatter deformatter = new BinaryFormatter ();
  789. using (FileStream fs = File.OpenRead (root + ".storage")) {
  790. Identities identities = (Identities) deformatter.Deserialize (fs);
  791. _applicationIdentity = identities.Application;
  792. _assemblyIdentity = identities.Assembly;
  793. _domainIdentity = identities.Domain;
  794. }
  795. }
  796. */
  797. [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)]
  798. private void SaveIdentities (string root)
  799. {
  800. Identities identities = new Identities (_applicationIdentity, _assemblyIdentity, _domainIdentity);
  801. BinaryFormatter formatter = new BinaryFormatter ();
  802. mutex.WaitOne ();
  803. try {
  804. using (FileStream fs = File.Create (root + ".storage")) {
  805. formatter.Serialize (fs, identities);
  806. }
  807. }
  808. finally {
  809. mutex.ReleaseMutex ();
  810. }
  811. }
  812. }
  813. }
  814. #endif