Author Topic: Move / Rename a file C#  (Read 11227 times)

0 Members and 1 Guest are viewing this topic.

A_LOTA_NOTA

  • Guest
Move / Rename a file C#
« on: April 20, 2011, 09:07:56 AM »
I’m trying to move an existing file to a directory that may or may not exist. I was surprised to find that C# doesn’t create the directory you are moving to if it doesn't exist. So is my only option to strip out the file name, check for the directory, then create it if it doesn't exist or is there a better way?

Code: [Select]
public static void MoveFile(string originalName, string newName)
        {
            FileInfo fileInfo = new FileInfo(@originalName);// this is to let me pass the orginal file name as a string
            DirectoryInfo dirInfo = null;

            if (!Directory.Exists(@newName))// if directory doesn't exist
            {
                dirInfo = new DirectoryInfo(@newName);
                dirInfo.Create();
            }// end if

            if (File.Exists(@originalName))// file exists. if not do nothing
            {
                fileInfo.MoveTo(newName);// move/rename it.
            }// end if
        }// end MoveFile

n.yuan

  • Bull Frog
  • Posts: 348
Re: Move / Rename a file C#
« Reply #1 on: April 20, 2011, 09:44:59 AM »
C# or VB.NET, they do not create a folder for you automatically. So, yes, you need to strip out the file name from the long pathed file name, and traverse along the path to make sure each folder in the path exists (and create it if not).

Thus, your code would potentially fail, if the path is like "C:\Folder1\folder2\fodler3\myfile.dwg" and "folder2" does not exists, because you only chek if "C:\folder1\folder2\folder3" exists or not and try to create folder3 without creating folder2 first.

And also make sure you would handle IOException properly (creating folder may fail due to file system access permission, for example).

A_LOTA_NOTA

  • Guest
Re: Move / Rename a file C#
« Reply #2 on: April 20, 2011, 09:52:16 AM »
C# or VB.NET, they do not create a folder for you automatically. So, yes, you need to strip out the file name from the long pathed file name, and traverse along the path to make sure each folder in the path exists (and create it if not).

Thank you, I just wanted to make sure there wasn't a better way of doing it.

Thus, your code would potentially fail, if the path is like "C:\Folder1\folder2\fodler3\myfile.dwg" and "folder2" does not exists, because you only chek if "C:\folder1\folder2\folder3" exists or not and try to create folder3 without creating folder2 first.

In the tests I have ran using "C:\Folder1\folder2\folder3\myfile.dwg" it will make all the folders including one called "myfile.dwg"

And also make sure you would handle IOException properly (creating folder may fail due to file system access permission, for example).

Thank you for the info. I'll have to look at that.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Move / Rename a file C#
« Reply #3 on: April 22, 2011, 03:36:45 AM »
A_LOTA_NOTA,
Have a play with this ..

Code - C#: [Select]
  1. using System;
  2. using System.IO;
  3.  
  4. using Autodesk.AutoCAD.Runtime;
  5. using Autodesk.AutoCAD.ApplicationServices;
  6. using Autodesk.AutoCAD.DatabaseServices;
  7. using Autodesk.AutoCAD.Geometry;
  8. using Autodesk.AutoCAD.EditorInput;
  9.  
  10. using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;
  11. using AcUtils = Autodesk.AutoCAD.Internal.Utils;
  12.  
  13. [assembly: CommandClass(typeof(FileStuff.MyCommands))]
  14.  
  15. namespace FileStuff
  16. {
  17.     public class MyCommands
  18.     {        
  19.         [CommandMethod("MoveFile", CommandFlags.Modal)]
  20.         public void MyCommand()
  21.         {
  22.             Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
  23.  
  24.             string newPath = @"c:\MyDir\A_Loto_Noto\Test1\";
  25.             string originalFileName = "K:\\Drawing112.Dwg";
  26.            
  27.             if( !File.Exists(originalFileName) )
  28.             {
  29.                 ed.WriteMessage("The Original file Does not exist: {0}", originalFileName);
  30.                 return;
  31.             }
  32.  
  33.             if( AssertFolder(newPath, ed) == false )
  34.             {
  35.                 return;
  36.             }
  37.             string newFileQualifiedName = newPath + Path.GetFileName(originalFileName);
  38.  
  39.             // Ensure that the target does not exist.
  40.             if( File.Exists(newFileQualifiedName) )
  41.             {
  42.                 File.Delete(newFileQualifiedName);
  43.             }
  44.  
  45.             File.Move(originalFileName, newFileQualifiedName );
  46.  
  47.             if( File.Exists(newFileQualifiedName) )
  48.             {
  49.                 ed.WriteMessage("The Original file was copied to: {0}", newFileQualifiedName);
  50.  
  51.             } else
  52.             {
  53.                 ed.WriteMessage("Call the Wambulance");
  54.             }
  55.         }
  56.  
  57.         /// <summary>
  58.         ///
  59.         /// </summary>
  60.         /// <param name="path"></param>
  61.         /// <param name="ed"></param>
  62.         /// <returns></returns>
  63.         public bool AssertFolder(string path, Editor ed)
  64.         {
  65.             bool returnVal = false;
  66.             try
  67.             {
  68.                 // Determine whether the directory exists.
  69.                 if( Directory.Exists(path) )
  70.                 {                  
  71.                     return true;
  72.                 }
  73.                 // ELSE, Try to create the directory.
  74.                 DirectoryInfo di = Directory.CreateDirectory(path);
  75.                 returnVal = Directory.Exists(path);
  76.  
  77.                 ed.WriteMessage("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
  78.                 returnVal = true;
  79.  
  80.             } catch( System.Exception e )
  81.             {
  82.                 ed.WriteMessage("The 'AssertFolder' process failed: {0}", e.ToString());
  83.             } finally
  84.             {
  85.             }
  86.             return returnVal;
  87.         }
  88.     }
  89. }
  90.  
  91.  
  92.  

kdub:edit code=csharp
« Last Edit: August 29, 2012, 01:46:20 AM by Kerry »
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Move / Rename a file C#
« Reply #4 on: June 08, 2011, 05:46:40 AM »

You're welcome :)
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

A_LOTA_NOTA

  • Guest
Re: Move / Rename a file C#
« Reply #5 on: June 08, 2011, 11:04:09 AM »

You're welcome :)


Sorry, Thank you Kerry. I've been busy at work and have not been able to mess with this yet. I don't get much time for programming.
« Last Edit: June 08, 2011, 11:11:51 AM by A_LOTA_NOTA »