C# question

0 comments

What does this code do? Are there any bugs? does the code
require refactoring?

static void
Cache(WindowsIdentity identity, FileInfo Source, FileInfo
Target, Dictionary<string, ReplaceContents>
rc)

{

  lock
(lockThis)

  {

  List<string> children = null;

  string
text = null;

  byte[]
data = null;

  DateTime?
Source_LastWriteTime = null;

  // Get target
last-modification time

  // Note:
.Exists returns false for Directories, hence the Attribute checking

  //  .Attributes returns -1 on error (such as
doesnt exist). Perhaps I should simply check this value? (would need further
testing).

  bool
Target_Exists = Target.Exists || (((int)Target.Attributes
!= -1) && ((Target.Attributes & FileAttributes.Directory)
== FileAttributes.Directory));

  DateTime?
Target_LastWriteTime = null;

  if
(Target_Exists)

   Target_LastWriteTime =
Target.LastWriteTime;

  //
Read/Enumerate Source using impersonation

  using
(identity.Impersonate())

  {

  try

  {

  if
(((int)Source.Attributes != -1) &&
((Source.Attributes & FileAttributes.Directory)
== FileAttributes.Directory))

  {

  children = new List<string>();

  foreach
(var child in Directory.EnumerateFileSystemEntries(Source.FullName))

  children.Add(new FileInfo(child).Name);

  }

  else
if (Source.Exists &&
((Target_LastWriteTime == null) ||
(Target_LastWriteTime.Value < Source.LastWriteTime)))

  {

  Source_LastWriteTime =
Source.LastWriteTime;

  if
(rc.ContainsKey(Source.Extension))

  text = File.ReadAllText(Source.FullName);

  else

  data = File.ReadAllBytes(Source.FullName);

  }

   }

  catch
(Exception ex)

  {

  //
Only swallow error if target already exists (assume cache has current version
of file/folder)

  if
(Target_Exists)

  return;

  else

   throw;

  }

  }

  // Source is
a Directory?

  if
(children != null)

  {

  if
(Target.Exists)

  Target.Delete();

  else
if (((int)Target.Attributes
== -1) || ((Target.Attributes & FileAttributes.Directory)
!= FileAttributes.Directory))

  Directory.CreateDirectory(Target.FullName);

  foreach
(var child in
children)

  Cache(identity, new FileInfo(Path.Combine(Source.FullName, child)), new FileInfo(Path.Combine(Target.FullName, child)), rc);

  }

  // Source is
a text file with a matching delegate for replacing its contents

  else if (text != null)

  {

  Directory.CreateDirectory(Target.DirectoryName);

   text =
rc[Source.Extension](Source.FullName, Target.FullName, text);

  File.WriteAllText(Target.FullName,
text);

  Target.LastWriteTime =
Source_LastWriteTime.Value;

  }

  // Source is
a file

  else if (data != null)

  {

  Directory.CreateDirectory(Target.DirectoryName);

  File.WriteAllBytes(Target.FullName,
data);

  Target.LastWriteTime =
Source_LastWriteTime.Value;

  }

  }

}

About the Author

Follow me


{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}