Moving a file in c# without renaming it - c#

I have a collection of XML files I am looping through and moving the files that have errors to another file location. However when I'm using the system.io.file.move function it requires me to specify a file name instead of moving the file path. Is there a way I can move the file from one location to another while keeping the same name? I am currently creating a name based on the position of the file in the array which isn't really feasible.
string ErrorPath = string.Format(#"{1}ErroredXml{0}.xml", errorLength, errorPaths);
//If type equals "add" then call add method else call update
if (Equals(type, typecomp))
{
//pass object to data access layer to add record
value.addNewGamePlay();
if (value.getGamePlayID() == 0)
{
//move to error file
System.IO.File.Move(value.getFile(), ErrorPath);
errorLength++;
}
}

You can use Path.GetFileName to extract the original file name and construct the destination path with it using Path.Combine:
var original = value.getFile();
var destinationPath = Path.Combine(errorPaths, Path.GetFileName(original));

Move method does not require to change name of file.
the second argument is not a new name to file but a new path to file
for example
first argument (sourceFileName)
#"c:\temp\MyTest.txt"
second argument (destFileName)
#"c:\temp2\MyTest.txt"
so file name is same "MyTest.txt" just position is changed.

Related

copy or move replace file and update version sharepoint CSOM

hi im using method for copy or move file on sharepoint. but i want to ask how to implement when it's duplicated it automatically replace and update version?
i've been try with this function but it's always
Microsoft.SharePoint.Client.ServerException: 'The destination file
already exists
public void CopyFile(string SrcUrl, string DestUrl)
{
MoveCopyOptions option = new MoveCopyOptions();
option.KeepBoth = false;
MoveCopyUtil.CopyFile(this.clientContext,SrcUrl,DestUrl,true,option);
this.clientContext.ExecuteQuery();
}
And my src
http://win-e636ggi1v13:55555/sites/srsrms/SRS%20Documents/Finance/fredytest/License%20Management.csv
and my Destination file
http://win-e636ggi1v13:55555/sites/srsrms/SRS%20Documents/Finance/paidi/Finance%20Folder/License%20Management.csv
#Mister Fredy,
Please set 'KeepBoth' to false and keep 'Overwrite' with true.
With the above settings, it will overwrite the existing file.
When both are false, it will prompt below error:
Another scenario is :
the destination file is not overwritten and a new file with a duplicate avoiding filename is created - i.e. a number is appended to the filename to avoid a duplicate.
BR

Copy and paste a file programmaticaly

Question Background:
I need to copy and paste (move) a file from one folder location to another.
Issue:
The File.Copy method of System.IO requires the that both parameters are of known file locations. I only know one file path location - in this case localDevPath. localQAPath is the folder path where I want the copied file to be moved too.
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
File.Copy(localDevPath, localQaPath);
Can anyone tell me how to go about carrying out this 'copy and paste' method I'm trying to implement.
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
FileInfo fi = new FileInfo(localDevPath);
fi.MoveTo(Path.Combine(localQaPath, fi.Name));
Assuming that these are user-provided paths and you can't simply include the filename in the second path, then you need to extract the last path element from localDevPath and then add it to localQaPath. You could probably do that with Path.GetFilename.
I'm guessing the issue here is that the filename is variable, in which case, you could do something like this to extract the filename from the full path of localDevPath:
string localDevPath = #"C:\Folder1\testFile.cs";
string localQaPath = #"C:\Folder2\";
string[] tokens = localDevPath.Split(#"\");
localQaPath += tokens[tokens.Length-1];
File.Copy(localDevPath, localQaPath);
Documentation on File.Copy is on MSDN. There is an overload that accepts a boolean, to allow overwriting if there is a naming conflict.
If what you want to do is move the file from one location to another, the method you are looking for is MoveTo. It is a method of the FileInfo class. There is a very complete example in the MSDN Library here: FileInfo.MoveTo Example

Finding the exact path of the file

I am using the fileUpload control. When I upload the file, I want to find the exact location of the file.
I tried using:
string fname= Server.MapPath(FileUpload2.FileName);
string fname= FileUpload2.FileName;
string fname= FileUpload2.PostedFile.FileName;
Numbers 2 & 3 gave me the name of the file. Number 1 gave me the the path of my website location. I do not know what is the difference between 2 and 3, why both gave me same results.
I read somewhere, that you cannot get the path. Is it true? If not, what code should I use?
There is no actual file path because a file uploaded to the server is simply held in memory.
The FileUpload control is just a wrapper around an HttpPostedFile instance, which itself is basically just a wrapper around an InputStream.
It's up to you to actually save the file somewhere. Until then it doesn't exist in any physical location.
The FileName property simply corresponds to the filename from the client's machine, minus the path. It has no correlation to anything on the server's file system.
There are a couple of different ways you can deal with the file.
Save The File To Disk:
The FileUpload control provides a SaveAs method that will allow you to save the file locally, or some UNC that you have access to.
FileUpload2.SaveAs("C:\\Temp\\" + FileUpload2.FileName);
Process The File In Memory:
Since you have access to the FileContent, you could simply manipulate and process the file directly. Assuming you know what type of file it is (txt, pdf, csv, etc...)
using (var sr = new StreamReader(FileUpload2.FileContent))
{
while ((var line = sr.ReadLine()) != null)
{
//Do something with 'line'
}
}

asp file upload control, which one should be use?

ok, i found this on internet to upload some files.
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
and this
//check to make sure a file is selected
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
what is the difference, which one to use? i got confuse. by the way, if i can store file path in database, and next time when i want to delete or see that file, how can i retrieve that? so let say, first i add a record to database and uploaded a .doc file / excel file, next time when i want to edit that record, i want to retrieve the uploaded file, and show it in UI. thanks.
use second one cause it will convert relative or virtual path to real path itself . .u should get path from db and use it to resolve the path the same way you are storing and do manipulation on it delete and etc. for displaying url="~/Files/yourfilename"
yourfilefromdb -u retrieve it from db
string filepath = Path.Combine(Server.MapPath("~/Files"), yourfilefromdb);
File.Delete(filepath);
for showing
if it accessible directly u can just write url="~/Files/yourfilefromdb"
The only difference in two code blocks posted you is in specifying file path.
In case 1, static location is specified to save the file. It can cause problem, if location to save files differ in your production environment. It will require rebuild in that case.
While, in case 2, location is specified using relative path. So, it will always save files at "/Files" location.
//if you already know your folder is: E:\ABC\A then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/ABC/A and you want to know the real path in the disk...
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);// they know the right path so .they using directly
FileUpload1.SaveAs(fileName);
}
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);// i don't know path is correct or not so they using Server.MapPath. . .
FileUpload1.SaveAs(fileName);
}

How to create a new path that contains the same path as the source but with a different root?

I'm about to develop a software in C# that must select random folders (in a scenario with 10.000 folders more or less) that follow these rules:
select only the ones which contains files;
the software must stop the selection when the size of selected folder is 8GB;
when I copy a single folder, I need to keep the whole path of that folder (if c:\folder\temp\hello is the copied one, I want to keep d:\COPIED\folder\temp\hello);
I think I will do somethings like:
analyze the whole list of folder starting from an assigned root;
select random "line" in this list, moving it to the "selected list", counting the size;
when I reach 8GB, I stop this first phase, and I start to copy it;
I think here it is not a big trouble. What do you think about? Any suggestions?
My real problem will to "recreate" the whole path for each single folder when I move it.
How can I do it? Create folder for each level with C# API or is there a workaround?
So the last paragraph is the question? I understand it in the following way:
How to create a new path that contains the same path as the source but
with a different root?
Then you can use the Path class and it's static methods + String.Substring to get the new path.
D:\Copied is your root destination folder which you use in Path.Combine. Then you have to add the old-path without it's root-folder(there is no method in Path for this, i'll use Substring):
var rootDest = #"D:\Copy"; // your root directory
var pathSource = #"C:\Test\Test.txt"; // a sample file
var root = Path.GetPathRoot(pathSource); // C:\
var oldPathWithoutRoot = pathSource.Substring(root.Length); // Test\Test.txt
var newPath = Path.Combine(rootDest, oldPathWithoutRoot); // D:\Copy\Test\Test.txt
Then use File.Copy to copy all files in the folder from the old to the new path.
You have to check if the directory exists and create it otherwise:
var targetDir = Path.GetDirectoryName(newPath);
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir); // D:\Copy\Test
}
File.Copy(pathSource, newPath);

Categories

Resources