Smart questions
Smart answers
Smart people
Join Tek-Tips Forums
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login




Remember Me
Forgot Password?
Join Us!

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.
Jobs from Indeed

Link To This Forum!

Partner Button
Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

subhadeep123 (Programmer) (OP)
17 Dec 09 13:06
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


 
Helpful Member!  jmeckley (Programmer)
17 Dec 09 15:08
you don't need to reference Visual Basic if you're using c#. Just use the objects within the File.IO namespace.

Quote:

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: Database Connection Management
FAQ732-7259: Keeping the UI responsive

subhadeep123 (Programmer) (OP)
17 Dec 09 20:50
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;
        }
    }
jmeckley (Programmer)
17 Dec 09 22:36
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: Database Connection Management
FAQ732-7259: Keeping the UI responsive

subhadeep123 (Programmer) (OP)
18 Dec 09 5:16

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





 
jmeckley (Programmer)
18 Dec 09 8:49
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: Database Connection Management
FAQ732-7259: Keeping the UI responsive

subhadeep123 (Programmer) (OP)
18 Dec 09 13:04
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?
subhadeep123 (Programmer) (OP)
18 Dec 09 13:19

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'
jmeckley (Programmer)
18 Dec 09 13:51
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: Database Connection Management
FAQ732-7259: Keeping the UI responsive

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close