How to move a file from a default directory to another? - c#

It sounds simple but it is not. I am trying to move a file that i made it like this:
string newFileName = string.Format("{0}-{1}-{2}-t{3:00}-{4:00}.txt", 2013, 10, 5, 05, 06);
It is going to look like: 2013-10-5-05-06.txt, from the default directory (..\bin\debug\2013-10-5-05-06.txt) to another directory (c:\Users\Public\Folder). I want to keep the name of the file so that other files having almost the same name (small difference between) being moved to the same folder. I tried several methods (Path.Combine(), string.Concat()..) without success.

Just use this snippet
string CurrentFileNameAndPath; //the path the file you want to move
string newPath; //only the new the folderPath
System.IO.FileInfo FileYouWantToMove = new System.IO.FileInfo(CurrentFileNameAndPath);
string NewFileNameAndPath = newPath + "\\" + FileYouWantToMove.Name; //remember that using fullname will get the folder and filename
FileYouWantToMove.MoveTo(NewFileNameAndPath);
So lets use this as an example i have this file C:/Dir1/file1.txt and I want to change its directory to C:/Dir2/ right? then it will be like this
string CurrentFileNameAndPath = #"C:/Dir1/file1.txt";
string newPath = #"C:/Dir2/";
System.IO.FileInfo FileYouWantToMove = new System.IO.FileInfo(CurrentFileNameAndPath);
string NewFileNameAndPath = newPath + "\\" + FileYouWantToMove.Name;
FileYouWantToMove.MoveTo(NewFileNameAndPath);
the result will the that file in C:/Dir1/file1.txt will be now in C:/Dir2/file1.txt it have been moved and maintened the same file name and extension

Something like this is actually pretty trivial
var srcFile = "..\bin\debug\2013-10-5-05-06.txt";
var destFolder = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
var destFile = Path.Combine(destFolder, Path.GetFileName(srcFile));
File.Move(srcFile, destFile);
Just keep in mind that Move can throw various exceptions e.g. IOException / UnauthorizedAccessException etc. so it would be wise to handle these where appropriate.

Related

rename file by adding an incrementing number to old file name c#

I'm writing my first Cocoa app in c#, its suppose to append/add numbers at the begging of a file name.
Users give only the path to the folder (for example with music), and for each file included in folder the program suppose to add incrementing numbers like
001_(old_fileName),
002_(old_fileName),
...,
092_(old_fileName)
etc,
Untill the end of files in given folder (by path).
There is no way to split a file name, cause file names are not known (may even include numbers itself). I've tried few possible options to solve this, but non of them works. Found few already asked question with changing names in c# but non of the results actually helped me.
The code under is the rest I've got at the moment, all non-working tries were firstly commented and later deleted. by NSAlert i see the path/name of each file in folder as a help. I would be more than happy to receive help
void RenameFunction()
{
string sPath = _Path_textBox.StringValue;
if (Directory.Exists(sPath))
{
var txtFiles = Directory.EnumerateFiles(sPath);
var txt2Files = Directory.GetFiles((sPath));
string fileNameOnly = Path.GetFileNameWithoutExtension(sPath);
string extension = Path.GetExtension(sPath);
string path = Path.GetDirectoryName(sPath);
string newFullPath = sPath;
int count = 1;
while (File.Exists(sPath))//newFullPath))
{
string tempFileName = string.Format(count + "_" + fileNameOnly + sPath);
//count++;
//string.Format("{0}{0}{0}{1}", fileNameOnly, count++);
newFullPath = Path.Combine(path, extension + tempFileName);
count++;
}
string[] fileEntities = Directory.GetFiles(newFullPath); //GetFileSystemEntries(sPath);//GetFiles(sPath);
//foreach (var _songName in fileEntities)
//{
// string tempFileName = count + "_" + fileNameOnly + sPath;
// //string.Format("{0}{0}{0}{1}", fileNameOnly, count++);
// newFullPath = Path.Combine(sPath ,extension + tempFileName);
// File.Move(sPath, newFullPath);
//}
foreach (var _songName in fileEntities)
{
AmountofFiles(_songName);
}
}
}
void AmountofFiles(string path)
{
var alert2 = new NSAlert();
alert2.MessageText = "mp3";
alert2.InformativeText = "AMOUNT OF MP3 FILES IS '{1}' : " + path;
alert2.RunModal();
}
Have you try use File.Move? Just move file to same path, but another name
File.Move("NameToBeRename.jpg","NewName.jpg");
There are multiple things which are not right with the code you share. The thing which want to achieve can be implemented using very simple approach.
All you need to do is retrieve all the files names with the full path from the directory and rename them one by one.
Follow the below code which demonstrates the above mentioned approach.
// Path of the directory.
var directroy = _Path_textBox.StringValue;
if (Directory.Exists(directroy))
{
//Get all the filenames with full path from the directory.
var filePaths = Directory.EnumerateFiles(directroy);
//Variable to append number in front of the file name.
var count = 1;
//Iterate thru all the file names
foreach (var filePath in filePaths)
{
//Get only file name from the full file path.
var fileName = Path.GetFileName(filePath);
//Create new path with the directory path and new file name.
var destLocation = Path.Combine(directory, count + fileName);
//User File.Move to move file to the same directory with new name.
File.Move(filePath, destLocation);
//Increment count.
count++;
}
}
I hope this helps you to resolve your issue.

Can't create folder structure with variable

I am trying to create a folder with a variable that can change, I am using
System.IO.Directory.CreateDirectory
When I hardcode a value like so:
var folder = #"C:\Users\Laptop\Documents\bot\random string here"
It creates that directory, but when I pass data to my method and try and use it like so:
var folder = #"C:\Users\Laptop\Documents\bot\" +
articlename.Replace(" ", "_");
System.IO.Directory.CreateDirectory(folder);
It doesn't create it nor break. How can I use the variable to create a folder like that?
My article is a random string like "hello this is a article yadda"
I solved by adding my paths together correctly as below
string path = root +"/"+ newfolder;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// To move a file or folder to a new location:
//System.IO.File.Move(fi.FullName, path);
}

Create Directory will multiple names passed by parameter C#

I have to create multiple folders as e.g.
Directory.CreateDirectory("PATH\\" + _year + "filetosave.txt");
while "PATH\\" is the full path where the folder will reside, _year is the parameter and "filetosave.txt" is the file which is to be saved in respective folder.
And at run time, it should create respective folders with years in the folder name containing respective files to save.
Whereas .CreateDirectory() method only accepts string path or string path, security access as parameters.
How will we create these parameterized folders?
How can we make a check that a specified directory already exists or not?
var path = Path.Combine("PATH\\", _year.ToString(), "filettosave.txt");
Directory.CreateDirectory(path);
Directory.CreateDirectory
Creates all directories and subdirectories in the specified path unless they already exist.
Emphasis mine.
As commented, use Path.Combine when trying to build system paths:
var root = "Path";
var year = "2016";
var filename = "filetosave.txt";
var path = Path.Combine(root, year, filename);
// path = Path\2016\filetosave.txt
Directory.CreateDirectory(path);
In general, use System.IO.Path.Combine to build paths. It simplifies this task.
string dir = System.IO.Path.Combine(rootPath, _year.ToString());
Directory.CreateDirectory(dir);
string file = System.IO.Path.Combine(dir, "filetosave.txt");
FileStream fs = File.Create(file)

How to move a file that has no file extension? C#

if (File.Exists(#"C:\\Users" + Environment.UserName + "\\Desktop\\test"))
{ /\
this file has no file extension
}
The file test has no extension and I need help to either move or rename this file to something with a extension
Having no extension has no bearing on the function.
Also, a rename is really just a move "in disguise", so what you want to do is
File.Move(#"C:\Users\Username\Desktop\test", #"C:\Users\Username\Desktop\potato.txt")
Please bear in mind the # before the string, as you haven't escaped the backslashes.
There's nothing special about extensionless files. Your code is broken because you use string concatenation to build a path and you're mixing verbatim and regular string literal syntax. Use the proper framework method for this: Path.Combine().
string fullPath = Path.Combine(#"C:\Users", Environment.UserName, #"Desktop\test");
if(File.Exists(fullPath))
{
}
You also should use the proper framework method to get the desktop path for the current user, see How to get a path to the desktop for current user in C#?:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fullPath = Path.Combine(desktopPath, "test");
Then you can call File.Move() to rename the file, see Rename a file in C#:
if(File.Exists(fullPath))
{
string newPath = fullPath + ".txt";
File.Move(fullPath, newPath);
}
You can get all files without extension in this way:
var files = Directory.EnumerateFiles(#"C:\Users\Username\Desktop\")
.Where(fn => string.IsNullOrEmpty(Path.GetExtension(fn)));
Now you can loop them and change the extension:
foreach (string filePath in filPaths)
{
string fileWithNewExtension = Path.ChangeExtension(filePath, ".txt");
string newPath = Path.Combine(Path.GetDirectoryName(filePath), fileWithNewExtension);
File.Move(filePath, newPath);
}
As you can see, the Path-class is a great help.
Update: if you just want to change the extension of a single file that you already know it seems that Dasanko has already given the answer.

saveFileDialog create new folder and save inside it

i wanna create backup data in my application I used saveFileDialog, so i can place backup file anywhere i want (Dekstop, drive D, etc)
my backup file will be db, image, video so i guess it's will be easier to place that in one folder let say it's "myBackup" folder (generate automatically with C#)
so if user wanna save in Dekstop all of backup data will be in ~C:\Users\Maju\Desktop\myBackup~
i already successfully generate folder but my file won't save inside that
mySaveFileDialog.FileName = "Backup Database " + dateTimeNow;
if (mySaveFileDialog.ShowDialog() == DialogResult.OK)
{
string fileAsal = System.IO.Path.Combine(Global.myDatabaseLocation, "data.mdb");
FileInfo fi = new FileInfo(mySaveFileDialog.FileName);
string nameFolder = "myBackup";
System.IO.Directory.CreateDirectory(#fi.DirectoryName + "\\" + nameFolder);
string path = System.IO.Path.Combine (fi.DirectoryName, "\\" + nameFolder);
string pathDestination = System.IO.Path.Combine(path, mySaveFileDialog.FileName);
System.IO.File.Copy(fileAsal, pathDestination, true);
}
Is not it easier to use FolderBrowserDialog?
mySaveFileDialog.FileName already includes the path to the file so you need to write
string pathDestination = System.IO.Path.Combine(path, System.IO.Path.GetFileName(mySaveFileDialog.FileName));

Categories

Resources