Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File and Folder Renaming 1

Status
Not open for further replies.

subhadeep123

Programmer
Dec 17, 2009
8
IN
In C# it is also possible.

The FileSystem class is in the namespace 'Microsoft.VisualBasic' and 'Microsoft.VisualBasic.FileIO'.
Those namespaces are in Microsoft.VisualBasic.dll library.

In your C# project, you need to add the reference to that
.dll by from the .NET section of the Add Reference dialog
and selecting Microsoft.VisualBasic


After that, you use that class as follows:
Microsoft.VisualBasic.FileSystem.Rename("D:/ABC/glass.jpg", "D:/ABC/glass1.jpg");

Or

Microsoft.VisualBasic.FileIO.FileSystem.Rename("D:/ABC/glass.jpg", "D:/ABC/glass1.jpg");


This snippet works for both file and folder renaming.

One good news, this is to the most extent is failsafe.

For example if you open a file/folder, then also you can
rename without any exception


 
you don't need to reference Visual Basic if you're using c#. Just use the objects within the File.IO namespace.
One good news, this is to the most extent is failsafe.

For example if you open a file/folder, then also you can
rename without any exception
what?
if the operation is successful no exception is thrown, it doesn't matter what language.
If the operation cannot be completed an exception should be thrown. this is where you start with debugging. if it silently failed that's even worse then blowing up, as you will never have any information about when, how or why it fails.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Hi Jason,

I didn't mean that it is only for C#. I only stated my
observation only for that built-in function.

I also didn't mean to say that it silently fails. It throws
exception when I am trying to rename a folder/file that
doesn't exist, but it successfully rename file/folder if
I open the folder or read the file when the program is
trying to rename that. I already checked and debugged with
that following code:

Still please tell me whether I am missing anything in
my understanding.

protected void btnRename_Click(object sender, EventArgs e)
{
try
{
Microsoft.VisualBasic.FileSystem.Rename("D:/ABC/glass.jpg", "D:/ABC/glass1.jpg");
lblMessage.Text = "SUCCESS!";
lblMessage.ForeColor = System.Drawing.Color.Green;

}
catch
{
lblMessage.Text = "FAILURE!";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
}
 
look into the System.IO namespace. there are all kinds of objects in there to manage files. no reference to VB required. also, your error handling is lacking. there are guidelines about the best practices for handling exceptions.
1. do *not* catch often. most times letting the exception bubble up is acceptable.
2. keep catch logic simple. log/wrap/throw
3. only catch exceptions you expect. catch(Exception e) the is usually not a good idea, except as a fail safe at the application level.
4. if you're not wrapping the exception to throw then you should log the details somewhere.

for example
Code:
try
{
   var file = new FileInfo(path to file);
   file.Move(new destination);
}
catch(IOException exception)
{
   log4net.LogManger.GetLogger(GetType()).Error(exception.Message, exception);
     ErrorMessage.Text = "An Error occured. review logs for details);
}

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 

Thanks for your suggestion.

Actually I have certain cases in my current project where
we need to rename a folder as well as update a table row
for a column that stores that folder path.

So we need to do 2 operations in atomic manner:
1. Update that field
2. Rename that folder.

I also used that Move() function in that project. But sometime
these scenarios are happening:

1. Table field is being updated, but
2. Folder is not being renamed giving exception such as
access violation

Or,

1. Table field is not updated and throwing exception when
database server is not up
2. And Folder is being renamed successfully.

In both cases, the application is going to the inconsistent
state.

For more clarification [Folder rename: Access Denied Error]:
1. The folder need to be renamed is under my web application
2. I have given IIS ASPNET user the necessary rights for
the folder
3. I was not traversing the folder when I ran the application.

What do you think the problem could be? And how I can keep
my application consistent with both folder and database issue?

Thanks and Regards,

Subhadeep





 
catch the exception and rollback the changes.
Code:
using(var connection = new SqlConnection())
using(var command = connection.CreateCommand())
{
   command.CommandText = sql statement;
   command.Parameters.Add(parameter);
   IDbTransaction transaction;
   try
   {
      connection.Open();
      transactions = connection.BeginTransaction();

      command.ExecuteNonReader();
      File.Move(source, destination);

      transactions.Commit();
   }
   catch (SqlException)
   {
      if(File.Exists(destination))
      {
          File.Move(destination, source);
      }
      transactions .RollBack();
      throw;
   }
   catch (IOException)
   {
      transactions .RollBack();
      throw;
   }
}
now I wouldn't recommend cramming all of this into one procedural block of code. for the purpose of demonstration all the code slapped together.

here are the key points.
1. dispose of ado.net objects. this is can be done explicitly with Dispose() or the keyword using
2. catch exceptions I expect.
3. catch the error, rollback the transaction, and throw the exception again to bubble up.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Hi Jason,

Thanks for your nice and thorow clarification. :)

But I though about there is some stored procedure in sql
server that can do certain file related operations, I saw
something and searching is there anything for renaming.

Then I will not need all those catch blocks and inter-
dependencies. What do you think?
 

I forgot to include, I tried that sql in my office and it is
working:

EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
go

EXEC master..xp_cmdshell 'RENAME D:\ABC1 ABC'
 
I don't know about that. I use ORM (object relational mapping) and dynamic sql instead of procs. I treat the database as a persistence structure. nothing more, nothing less. that means CRUD (create, read, update, delete) operations. all behavior is defined within the application code.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top