turrier.fr

Source : ct|22.09.09

< Tutorials Computer, Multimedia, Chinese

Rename or move a file with csharp or VB

The File class of the System.IO namespace (mscorlib.dll Assembly) provides methods to create, copy, move, rename and opening files.
We can access the methods of the File class without creating an instance of this classe. The Move method, of the File class, allows to assign a new name to a file and possibly a new location.

Suppose we want to give the new name "nouveaunom.dat" to the file "monfichier.dat". With the Framework .net 2.0 and Sharpdevelop 2.2, create a C# console program called "EssaiNomFichier" for example.

Place the following source code in Program.cs.

using System;
using System.IO;
namespace EssaiNomFichier
{
class Program
{
public static void Main(string[] args)
{
string nom ="monfichier.dat";
string nouveau nom ="nouveaunom.dat";
File.Move(nom, nouveaunom);
Console.WriteLine ("Opération effectuée !");
Console.ReadKey(true);
}
}
}

In VB, the equivalent code is :

Imports System
Imports System.IO
Module Program
Sub Main()
Dim nom as String ="monfichier.dat"
Dim nouveaunom as String ="nouveaunom.dat"
File.Move(nom, nouveaunom)
Console.WriteLine ("Opération effectuée !")
Console.ReadKey(True)
End Sub
End Module

Copy the file to rename in the same directory as the program. Build the solution (F8) and then run the program. In the program directory, the file is renamed.

Program executed

File renamed

The following code in VB allows to change the file name "monfichier.dat", which is placed in the program directory, and to move it to C :

Imports System
Imports System.IO
Module Program
Sub Main()
Dim nom as String ="monfichier.dat"
Dim nouveaunom as String ="C:\\nouveaunom.dat"
File.Move(nom, nouveaunom)
Console.WriteLine ("Opération effectuée !")
Console.ReadKey(True)
End Sub
End Module


Valid XHTML 1.0 Transitional

© http://turrier.fr (2007)