从源和目标移动文件 [英] Moving files from source and destination

查看:74
本文介绍了从源和目标移动文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这里根据我正在检索文件和检索文件的日子我存储它并将存储的文件从一个文件夹移动到另一个文件夹.....我正在做所有这个基于线程的操作



这里是我的代码

Hi,
here based on the days i am retreving the files and retreived files i am storing it and moving the stored files from one folder to another folder.....i am doing all this operation based on threads

here is my code

   private void btnOpenDicom_Click(object sender, EventArgs e)
       {
           SQLHelper admin = new SQLHelper();
           try
           {
               maxArchivdays = admin.GetMaxArchivalDays();
               var dict = _dict;
               var path = admin.GetSourceDestination();
               string SourcePath = path.Rows[0]["SourcePath"].ToString();
               string DestinationPath = path.Rows[0]["TargetPath"].ToString();
               var FilesList = Directory.GetFiles(SourcePath).Select(f => new FileInfo(f)).Where(f => f.CreationTime < DateTime.Now.Subtract(TimeSpan.FromDays(20))).ToList();
               var Files = FilesList.ToList();
               var Write = admin.GetPacsDefault(SourcePath);
               bool OverWrite = Convert.ToBoolean(Write.Rows[0]["Overwrite"]);
               if (Files !=null)
               {
                   foreach (var items in Files)
                   {
                       var dictonary = dict;
                       FileInfo filename = items;
                       DicomThreadValues DTV = new DicomThreadValues();
                       DTV.filename = filename;
                       DTV.dictKeyValue = dictonary;
                       DTV.Destination = DestinationPath;
                       DTV.SourcePath = SourcePath;
                       DTV.overWrite = OverWrite;
                       ThreadPool.SetMaxThreads(1, 1);
                       ThreadPool.QueueUserWorkItem(FileCopy, DTV);

                   }
               }
               else
               {
                   MessageBox.Show("There are no files to be Archive");
               }
           }
           catch (Exception ex)
           {
               bool rethrow = exManager.HandleException(ex, "SDExceptionPolicy");
               if (rethrow)
                   throw;
           }

       }


  public void  FileCopy(object data)
       {
           SQLHelper admin = new SQLHelper();
           var path = admin.GetSourceDestination();
           string SourcePath = path.Rows[0]["SourcePath"].ToString();
           string DestinationPath = path.Rows[0]["TargetPath"].ToString();
           FileInfo FileName;
           DicomThreadValues DTV = (DicomThreadValues)data;
           var dict = DTV.dictKeyValue;
           FileName = DTV.filename;
           bool overWrite = DTV.overWrite;
           List<string> keys = new List<string>(dict.Keys);
           List<int> Vals = new List<int>(dict.Values);
           DicomDecoder decoder = new DicomDecoder();
           decoder.DicomFileName = FileName.FullName;
           var def = admin.GetPacsDefault(SourcePath);
           var defaultArchivDays = def.Rows[0]["ArchivalDays"];
           DefaultArchivDays = Convert.ToInt32(defaultArchivDays);
           DicomTags dicom = new DicomTags();
           dicom.tag = "xyz";
           dicom.tagDesc = "this is a dicom tags";
           dicom.tagValue = "dcome123";
           string XML = SerializeObjectToXML(dicom);
           var modalityCheck = dict.Keys.Any(key => key.Contains(decoder.dicomModality.Trim()));
           if (modalityCheck)
           {
               DicomProcessor dicomProcessor = new DicomProcessor();
               DTV.result = dicomProcessor.ReadDICOMFile(FileName, dict);
           }
           else
           {
               var LastAccesed = FileName.LastAccessTime;
               DateTime CurrentDate = DateTime.Now;
               TimeSpan date = CurrentDate - LastAccesed;
               var Days = Convert.ToInt32(date.TotalDays);
               if (Days < DefaultArchivDays)
               {
                   DTV.result = admin.InsertPacsDicomArchival(FileName.FullName, FileName.Length, decoder.dicomModality, LastAccesed, CurrentDate, XML);
               }
           }
           // Check if the file can be archived....B
           if (DTV.result > 0)
           {
               //  FileArchive dest = new FileArchive();
               FrmDicom dest = new FrmDicom();
               dest.MoveFilesControl(SourcePath, DestinationPath, overWrite);
           }
           //if archived, then move the file to destination folder
           //Delete file from source
           //create sym link
           // if any error occurs during filecopy/delete/sym link creation, then notify it in log and try to do corrective actions
           //generate report

       }

  public void MoveFilesControl(string source, string destination, bool overwrite)
       {
           System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(source);
           SQLHelper admin = new SQLHelper();

           try
           {
               if ((inputDir.Exists))
               {
                   var FilesList = Directory.GetFiles(source).Select(f => new FileInfo(f)).Where(f => f.CreationTime < DateTime.Now.Subtract(TimeSpan.FromDays(20))).ToList();


                   var Files = FilesList.ToList();
                   foreach (System.IO.FileInfo eachfile in Files)
                   {
                       var File = Path.GetFileName(eachfile.ToString());

                       if (eachfile.CreationTime < DateTime.Now.Subtract(TimeSpan.FromDays(20)))
                       {
                           DicomThreadValues FTD = new DicomThreadValues();

                           FTD.Destination = destination;
                           FTD.overWrite = overwrite;
                           FTD.filename = eachfile;
                           ThreadPool.SetMaxThreads(1, 1);
                           ThreadPool.QueueUserWorkItem(MoveFile, FTD);
                       }
                   }
               }
           }
           catch (Exception ex)
           {
               bool rethrow = exManager.HandleException(ex, "SDExceptionPolicy");
               if (rethrow)
                   throw;
           }
       }

 private void MoveFile(object data)
       {
           try
           {
               DicomThreadValues FTD = (DicomThreadValues)data;
               System.IO.DirectoryInfo outputDir = new System.IO.DirectoryInfo(FTD.Destination);
               int id = System.Threading.Thread.CurrentThread.ManagedThreadId;
            //   string CreateLogs;
               FileInfo CreateLogs;

               var filepath = Path.GetDirectoryName(FTD.filename.ToString());
               var fileName = Path.GetFileName(FTD.filename.ToString());
               var fileNameOnly = Path.GetFileNameWithoutExtension(fileName);


              var doesExist = new DirectoryInfo(FTD.Destination).GetFiles(fileName, SearchOption.AllDirectories).Any();

               var name = FTD.Destination +'\\'+ fileName;

               DirectoryInfo di = new DirectoryInfo(FTD.Destination);
               var getfileName = di.GetFiles(fileName).ToList();
               if (!(outputDir.Exists))
               {
                   outputDir.Create();
               }
               if ((FTD.overWrite))
               {


                   if (doesExist)
                   {

                       var fileNameExtension = Path.GetExtension(FTD.filename.ToString());
                       string oldPathFile = Path.Combine(filepath, fileName);
                       string old = name;
                       string currentPath = FTD.Destination + "\\" + fileNameOnly + fileNameExtension;
                       var current = FTD.filename.FullName;
                       string Rename = "OLD";
                       string fullFileName = String.Format("{0}_{1}{2}", fileNameOnly, Rename, fileNameExtension);


                       System.IO.File.Move(oldPathFile, FTD.Destination + '\\' + fullFileName);
                       string path = Path.Combine(FTD.Destination, fullFileName);

                   }
                   else
                   {
                       CreateLogs = FTD.filename.CopyTo(System.IO.Path.Combine(outputDir.FullName, FTD.filename.Name), true);
                       // FTD.filename.CopyTo(System.IO.Path.Combine(outputDir.FullName, FTD.filename.Name), true);

                       if (CreateLogs != null)
                       {
                           ReportLogs(FTD.filename.ToString(), id);
                       }

                   }
               }



               else
               {
                   if (((System.IO.File.Exists(System.IO.Path.Combine(outputDir.FullName, FTD.filename.Name))) == false))
                   {
                       CreateLogs = FTD.filename.CopyTo(System.IO.Path.Combine(outputDir.FullName, FTD.filename.Name), false);
                       if (CreateLogs != null)
                       {
                           ReportLogs(FTD.filename.ToString(), id);
                       }

                   }
               }




               System.IO.File.Delete(FTD.filename.FullName);

           }
           catch (Exception ex)
           {
               bool rethrow = exManager.HandleException(ex, "SDExceptionPolicy");
               if (rethrow)
                       throw;
           }
       }

      public string GetAppDirectory()
      {
          string _path = "";
          try
          {
              _path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(frmPolicyEditor)).CodeBase);
              _path = _path.Replace("file:\\", "");

              if (!_path.EndsWith("\\"))
                  _path = _path + "\\";
          }
          catch (Exception)
          {
              throw;
          }
          return _path;
      }

      public void ReportLogs(string files, int id)
      {
          try
          {

              string _LogPath = GetAppDirectory() + "Report";

              string _LogInPath = GetAppDirectory() + DateTime.Now.ToString("dd-MM-yyyy");
              if (!System.IO.Directory.Exists(_LogPath))
              {
                  System.IO.Directory.CreateDirectory(_LogPath);
              }
              _LogPath += "\\" + DateTime.Now.ToString("yyyyMMdd");
              if (!System.IO.Directory.Exists(_LogPath))
              {
                  System.IO.Directory.CreateDirectory(_LogPath);
              }

              string _LogFile = _LogPath + "\\" + DateTime.Now.ToString("yyyy-dd-MMM---HH-mm-ss-fff") + "ThreadID--  " + id + ".log";

              StreamWriter _LogSW = new StreamWriter(_LogFile, true);
              _LogSW.WriteLine("-> " + "" + files + "  " + DateTime.Now.ToString() + Environment.NewLine + Environment.NewLine);
              _LogSW.Close();
              _LogSW.Dispose();

          }
          catch (Exception ex)
          {
              bool rethrow = exManager.HandleException(ex, "SDExceptionPolicy");
              if (rethrow)
                  throw;
          }

public static string SerializeObjectToXML(object item)
       {
           try
           {
               string xmlText;
               Type objectType = item.GetType();
               XmlSerializer xmlSerializer = new XmlSerializer(objectType);
               MemoryStream memoryStream = new MemoryStream();
               using (XmlTextWriter xmlTextWriter =
                   new XmlTextWriter(memoryStream, Encoding.UTF8) { Formatting = Formatting.Indented })
               {
                   xmlSerializer.Serialize(xmlTextWriter, item);
                   memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                   xmlText = new UTF8Encoding().GetString(memoryStream.ToArray());
                   memoryStream.Dispose();
                   return xmlText;
               }
           }
           catch (Exception e)
           {
               System.Diagnostics.Debug.Write(e.ToString());
               return null;
           }
       }
      }


每当我将文件从一个文件夹移动到另一个文件夹时,此代码中的
正在移动,但在源路径再次文件是那里......



,错误来了


in this code whenever i am moving files from one folder to another folder the files are moving but in sourcepath again the files are there ......

and the error comes is

HandlingInstanceID: 12d21581-ef29-4d27-8da1-87c431b5dcbe
An exception of type 'System.IO.IOException' occurred and was caught.
---------------------------------------------------------------------
02/16/2014 13:56:21
Type : System.IO.IOException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : The process cannot access the file because it is being used by another process.
Source : mscorlib
Help link : 
Data : System.Collections.ListDictionaryInternal
TargetSite : Void WinIOError(Int32, System.String)
HResult : -2147024864
Stack Trace :    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.__Error.WinIOError()
   at System.IO.File.InternalMove(String sourceFileName, String destFileName, Boolean checkHost)
   at System.IO.File.Move(String sourceFileName, String destFileName)
   at PACSPolicyManager.FrmDicom.MoveFile(Object data) in f:\Pacs\PACSArchivalSystem\ElitePACSManager\PACSPolicyManager\FrmDicom.cs:line 317



请帮我这个


pls help me with this

推荐答案

查看所有代码有点困难。



但我可以给你一些关于以下问题的提示。
Going through all the code is a bit tough.

But I can give you some hint regarding the following issue.
Quote:

消息:进程无法访问该文件,因为它正由另一个进程使用。

Message : The process cannot access the file because it is being used by another process.

这意味着在您尝试之前要在代码中移动文件,它已经在其他地方打开或使用。您的代码或系统中的任何其他程序。



您需要关闭并处理代码中使用的所有文件对象。如果文件被任何其他程序使用,则关闭程序和文件,然后再次运行代码。

This means the before you try to move the file in code, it is already opened or used somewhere else. Either in your code or by any other program in your system.

You need to close and dispose all the file objects used in your code. If file is used by any other programs, then close the program and file, then run your code again.


这篇关于从源和目标移动文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆