Renaming a File - c#

Guys I am trying to remane a file (adding _DONE to its name)
my researches showed that File.move(OLDNAME,NEWNAME) is what I needed.
Thus,
I did,
try
{
string oldname = name;
//XYZ_ZXX_ZZZ
string newName = ToBeTested + "_DONE.wav";
//rename file
//NOTE : OldName is already in format XYZ_III_SSS.wav
File.Move(oldname, newName);
}
catch (Exception exRename)
{
string ex1 = exRename.ToString();
//logging an error
string m = "File renaming process failed.[" + ex1 + "]";
CreateLogFile(p, m);
}
But It does not bears any result (File is not renamed) but the exception is logged.
as such
System.IO.FileNotFoundException: Could not find file 'C:\Users\Yachna\documents\visual studio 2010\Projects\FolderMonitoringService_RCCM\FolderMonitoringService_RCCM\bin\Debug\54447874_59862356_10292013_153921_555_877_400_101.wav'.
File name: 'C:\Users\Yachna\documents\visual studio 2010\Projects\FolderMonitoringService_RCCM\FolderMonitoringService_RCCM\bin\Debug\54447874_59862356_10292013_153921_555_877_400_101.wav'
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.Move(String sourceFileName, String destFileName)
at RCCMFolderMonitor.Monitor.OnChanged(Object source, FileSystemEventArgs e) in C:\Users\Yachna\documents\visual studio 2010\Projects\FolderMonitoringService_RCCM\RCCMFolderMonitor\Monitor.cs:line 209]
What did i do wrong ?

I guess that the file does not exist in the same folder as the application.
You will have to include the path in addition to the filename.
File.Move(path + oldname, path + newName);

From the StackTrace it seems that you are trying to move/rename the file whilst you receive the OnChanged event of a FileSystemWatcher component. If this is true this means that another application is writing/changing the file that you are trying to move/rename.
This could result in the above error message. The file exists, but you cannot get access to it until the other application closes it.

Without including the path of your file, Visual Studio looks for the file in your Debug directory. This is the reason of the error.
You have to include the full path of your file using the method Path.Combine of System.IO namespace:
string myDirectory = #"C:\Files";
string myFileName = "myFile.wav";
string myNewFileName = "myFileNew.wav";
string myFileFullPath = Path.Combine(myDirectory, myFileName);
string myNewFileFullPath = Path.Combine(myDirectory, myNewFileName);
Console.WriteLine(myFileFullPath); // it writes to Console: C:\Files\myFile.wav
//Then you can rename the file
File.Move(myFileFullPath, myNewFileFullPath);

Related

Access files from Network shared folder

I am accessing one folder with csv file under it by c# code. I have network path like "\NL0000NAS0007.dir.xyz.com\webtest\SERVERS\NLWSL086\personnel\people\PROD". While calling with below code it is appending "c:" earlier to this url so I am not able to get the files.
Below is my code snippet.
{
try
{
WriteLogFile.WriteLog(this.Configuration.GetValue<string>("logFile"), "Copy CSV File to Server", MessageType.Info);
//string projectPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string projectPath = #"D:\Paracomcsv\";
string folderName = Path.Combine(projectPath, "CsvFiles_" + DateTime.Now.ToString("MM_dd_yyyy"));
string[] files = Directory.GetFiles(sourcePath);
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
if (files.Length > 0)
{
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
var fileName = Path.GetFileName(s);
var destFile = Path.Combine(folderName, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
WriteLogFile.WriteLog(this.Configuration.GetValue<string>("logFile"), "File Doesn't Exist", MessageType.Error);
}
}
catch (Exception ex)
{
WriteLogFile.WriteLog(this.Configuration.GetValue<string>("logFile"), ex.Message, MessageType.Error);
throw ex;
}
}
I am getting the error while calling Directory.GetFiles. Anyone had the same issue, if yes please let me know how to call remote network shared file.
Thanks
The code snippet cant be the full source code. It is unclear how the variables are initialised. But given your network path of "\NL0000NAS0007.dir.xyz.com\webtest\SERVERS\NLWSL086\personnel\people\PROD" it is very clear, that it doesnt function. The path starts with a single \ character, so the System.IO API assumes you mean a relative path to whatever is the current directory or drive . And this could be "C:"...

Directory.CreateDirectory throws an exception, but only with .NET core?

I'm trying to log a line to a file, but unfortunately I hit a problem when the directory doesn't exist, the app tries to automatically create the directory and file. It works fine on .NET framework, but not core.
_filePath has the contents of (at compile time)
_filePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location + "/resources/logging/");
Which results in
_filePath = "B:\\App\\App\\bin\\Debug\\netcoreapp2.0\\App.Core.dll\\resources\\logging"
An exception text is printed, here is the content.
System.IO.IOException: 'Cannot create
'B:\App\App\bin\Debug\netcoreapp2.0\App.Core.dll' because
a file or directory with the same name already exists.'
Here is the line which throws the above error.
Directory.CreateDirectory(_filePath);
Full method
private void LogToFile(string file, string content)
{
var fullPath = Path.Combine(_filePath, file);
if (!Directory.Exists(_filePath))
{
Directory.CreateDirectory(_filePath);
}
if (!File.Exists(fullPath))
{
File.Create(fullPath);
}
using (var streamWriter = new StreamWriter(_filePath + file, true))
{
streamWriter.WriteLine(content);
}
}
The code you provided fails with full framework as well. The issue is that the Assembly.Location property returns the full path to the currently running assembly (exe or .dll). Trying to create a subdirectory under that will always fail.
Instead, you should use Path.Combine the directory part of the Location property with the subfolder (and then combine the result of that with the filename):
var folder = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"resources",
"logging");
var fullPath = Path.Combine(folder, file);
Directory.CreateDirectory(folder);
This results in an invalid argument to GetDirectoryName():
_filePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location + "/resources/logging/");
First, get the folder where the assembly is, then add on the rest of the path:
_filePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/resources/logging/";

Cannot move a file to another folder. Error returns on a wrong path

Here's my code in moving excel file to be specific..
if (Directory.GetFiles(destinationPath, "*.xls").Length != 0)
{
//Move files to history folder
string[] files = Directory.GetFiles(destinationPath); //value -- D://FS//
foreach (string s in files)
{
var fName = Path.GetFileName(s); //12232015.xls
var sourcePath = Path.Combine(destinationPath, fName);
var destFile = Path.Combine(historyPath, fName); // -- D://FS//History
File.Move(fName, destFile);
}
}
But it gets an error of
Could not find file 'D:\Project\ProjectService\bin\Debug\12232015.xls'.
Why it finds under my project not on the specific folder i set?
Thank you.
You're only using the name of the file:
var fName = Path.GetFileName(s); //12232015.xls
//...
File.Move(fName, destFile);
Without a complete path, the system will look in the current working directory. Which is the directory where the application is executing.
You should use the entire path for the source file:
File.Move(sourcePath, destFile);
Explicitly specifying the full path is almost always the best approach. Relative paths are notoriously difficult to manage.
There is an Logical error. Change
File.Move(fName, destFile);
to
File.Move(sourcePath, destFile);
as fName only contains file name and not fullpath. The file is checked in working directory.

Copying an image file to an empty folder in using WPF C#

After going through all the related stuff to copying files i am unable to find an answer to my
problem of an exception occurring while i was trying to copy a file to an empty folder in WPF application. Here is the code snippet.
public static void Copy()
{
string _finalPath;
foreach (var name in files) // name is the filename extracted using GetFileName in a list of strings
{
_finalPath = filePath; //it is the destination folder path e.g,C:\Users\Neha\Pictures\11-03-2014
if(System.IO.Directory.Exists(_finalPath))
{
_finalPath = System.IO.Path.Combine(_finalPath,name);
System.IO.File.Copy(name, _finalPath , true);
}
}
}
While debugging exception is occuring at file.copy() statement which says
"FileNotFoundException was unhandled" could not find file
i already know about the combining path and other aspects of copy but i dont know why this exception is being raised.
I am a noob to WPF please help.........
Use following code:
public static void Copy()
{
string _finalPath;
var files = System.IO.Directory.GetFiles(#"C:\"); // Here replace C:\ with your directory path.
foreach (var file in files)
{
var filename = file.Substring(file.LastIndexOf("\\") + 1); // Get the filename from absolute path
_finalPath = filePath; //it is the destination folder path e.g,C:\Users\Neha\Pictures\11-03-2014
if (System.IO.Directory.Exists(_finalPath))
{
_finalPath = System.IO.Path.Combine(_finalPath, filename);
System.IO.File.Copy(file, _finalPath, true);
}
}
}
The GetFileName ()
only returns the actual name of the file (drops the path) what you want is a full path to the file. So you getting an exception because the 'name' does not exist on your drive (path is unknown)
You're variable, name, is most likely just the file name (i.e. something.jpg). When you use the File.Copy(...) method, if you do not supply an absolute path the method assumes a path relative to the executable.
Basically, if you are running your app in, for example, C:\Projects\SomeProject\bin\Debug\SomeProject.exe, then it is assuming your file is C:\Projects\SomeProject\bin\Debug\something.jpg.

System.IO.File.Move error - Could not find a part of the path

I have a sync software, which loads CSV files from "Incoming" folder, processes them and then moves them to the "Archive" folder.
Today, I saw the following error with this sync software:
[23/06/2014 00:06:04 AM] : Failed to move file from
D:\IBI_ORDER_IMPORTER_FTP_SERVER\Template3\Fifty &
Dean\Incoming\5A040K___d6f1ca45937b4ceb98d29d0db4601bf4.csv to
D:\IBI_ORDER_IMPORTER_FTP_SERVER\Template3\Fifty &
Dean\Archive\5A040K___d6f1ca45937b4ceb98d29d0db4601bf4.csv - Could not
find a part of the path.
Here's a snippet taken out of the sync software, where the file is processed and moved:
public static void ProcessSingleUserFile(Int32 TemplateId, String ImportedBy, String FilePath)
{
// Always Rename File To Avoid Conflict
string FileName = Path.GetFileNameWithoutExtension(FilePath);
String NewFilePath = FilePath.Replace(FileName, Utils.RandomString() + "___" + FileName);
File.Move(FilePath, NewFilePath);
FilePath = NewFilePath;
// Log
SyncUtils.ConsoleLog(String.Format("Processing [ {0} as {1} ] By [ {2} ] On Template [ #{3} ]",
FileName + ".csv",
Path.GetFileName(FilePath),
ImportedBy,
TemplateId));
// Init
List<OrderDraft> myOrderDrafts = new List<OrderDraft>();
// Parsed Based On Template Id
if (TemplateId == Settings.Default.Multi_Order_Template_Id)
{
// Try Parse File
myOrderDrafts = Utils.ParseMultiImportFile(TemplateId, ImportedBy, FilePath, true);
}
else
{
// Try Parse File
myOrderDrafts.Add(Utils.ParseImportFile(TemplateId, ImportedBy, FilePath, true));
}
// Process Orders
foreach (OrderDraft myOrderDraft in myOrderDrafts)
{
/* code snipped */
}
// Archive File
File.Move(FilePath, FilePath.Replace("Incoming", "Archive"));
}
Any idea what this error means? and how to circumvent it?
I wrote a cut down version of the above to test this in a controlled environment and I am not getting the error with this code:
static void Main(string[] args)
{
try
{
string baseDir = #"C:\Users\Administrator\Desktop\FTP_SERVER\Template3\Fifty & Dean\Incoming\";
string[] filePaths = Directory.GetFiles(baseDir, "*.csv");
foreach (string filePath in filePaths)
{
// do some work here ...
// move file
string newFilePath = filePath.Replace("Incoming", "Archive");
File.Move(filePath, newFilePath);
Console.WriteLine("File successfully moved");
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Console.ReadKey();
}
You need to include the checks to make sure that the paths exist at runtime and check the output, something very simple like:
if(!Directory.Exists(Path.GetDirectoryName(filePath)))
{
Console.WriteLine("filePath does not exist: " + filePath);
}
if(!Directory.Exists(Path.GetDirectoryName(newFilePath)))
{
Console.WriteLine("newFilePath does not exist: " + newFilePath);
}
File.Move(filePath, newFilePath);
The reason I am suggesting this method is due to a possibility that the paths momentarily become available or not under the multi-tasking OSs depending on a multitude of factors: network connectivity, permissions (pushed down by GPO at any time), firewall rules, AV exclusions getting blown away etc. Even running low on CPU or RAM may create issues. In short, you never know what exactly occurred when your code was running if you are only checking the paths availability after the fact.
Or if your issue is intermittent, you can try and catch the error and write information to some sort of a log similarly to below:
try
{
File.Move(filePath, newFilePath);
}
catch(Exception ex)
{
if(!Directory.Exists(Path.GetDirectoryName(filePath)))
{
Console.WriteLine("filePath does not exist: " + filePath);
}
if(!Directory.Exists(Path.GetDirectoryName(newFilePath)))
{
Console.WriteLine("newFilePath does not exist: " + newFilePath);
}
}
"Could not find a part of the path" exception could also thrown from File.Move if argument used was longer than MAX_PATH (260) in .NET Framework.
So I prepend the path I used with long path syntax before passing to File.Move and it worked.
// Prepend long file path support
if( !packageFile.StartsWith( #"\\?\" ) )
packageFile = #"\\?\" + packageFile;
See:
How to deal with files with a name longer than 259 characters?
I have this
Could not find a part of the path
happened to me when I
File.Move(mapfile_path , Path.Combine(newPath, mapFile));
. After some testing, I find out our server administrator has blocked any user application from writing to that directory in that [newPath]!
So, right click on that directory to observe the rights matrix on Security tab to see anything that would block you.
Another cause of DirectoryNotFoundException "could not find a part of the path" thrown by File.Move can be spaces at the end of the directory name. Consider the following code:
string destinationPath = "C:\\Folder1 "; //note the space on the end
string destinationFileNameAndPath = Path.Combine(destinationPath, "file.txt");
if (!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationPath);
File.Move(sourceFileNameAndPath, destinationFileNameAndPath);
You may expect this code to succeed, since it creates the destination directory if it doesn't already exist, but Directory.CreateDirectory seems to trim the extra space on the end of the directory name, whereas File.Move does not and gives the above exception.
In this circumstance, you can workaround this by trimming the extra space yourself, e.g. (depending on how you load your path variable, the below is obviously overkill for a hard-coded string)
string destinationPath = "C:\\Folder1 ".Trim();

Categories