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
Related
I've got a folder:
c:\test
I'm trying this code:
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test");
I get exception:
File already exists
The output directory definitely exists and the input file is there.
What you need is:
if (!File.Exists(#"c:\test\Test\SomeFile.txt")) {
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test\SomeFile.txt");
}
or
if (File.Exists(#"c:\test\Test\SomeFile.txt")) {
File.Delete(#"c:\test\Test\SomeFile.txt");
}
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test\SomeFile.txt");
This will either:
If the file doesn't exist at the destination location, successfully move the file, or;
If the file does exist at the destination location, delete it, then move the file.
Edit: I should clarify my answer, even though it's the most upvoted!
The second parameter of File.Move should be the destination file - not a folder. You are specifying the second parameter as the destination folder, not the destination filename - which is what File.Move requires.
So, your second parameter should be c:\test\Test\SomeFile.txt.
You need to move it to another file (rather than a folder), this can also be used to rename.
Move:
File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test\SomeFile.txt");
Rename:
File.Move(#"c:\test\SomeFile.txt", #"c:\test\SomeFile2.txt");
The reason it says "File already exists" in your example, is because C:\test\Test tries to create a file Test without an extension, but cannot do so as a folder already exists with the same name.
Personally I prefer this method.
This will overwrite the file on the destination, removes the source file and also prevent removing the source file when the copy fails.
string source = #"c:\test\SomeFile.txt";
string destination = #"c:\test\test\SomeFile.txt";
try
{
File.Copy(source, destination, true);
File.Delete(source);
}
catch
{
//some error handling
}
You can do a P/Invoke to MoveFileEx() - pass 11 for flags (MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
static extern bool MoveFileEx(string existingFileName, string newFileName, int flags);
Or, you can just call
Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(existingFileName, newFileName, true);
after adding Microsoft.VisualBasic as a reference.
With C# on .Net Core 3.0 and beyond, there is now a third boolean parameter:
In .NET Core 3.0 and later versions, you can call Move(String, String, Boolean) setting the parameter overwrite to true, which will replace the file if it exists.
Source: Microsoft Docs
For all other versions of .Net, this answer is the best. Copy with Overwrite, then delete the source file. This is better because it makes it an atomic operation. (I have attempted to update the MS Docs with this)
If file really exists and you want to replace it use below code:
string file = "c:\test\SomeFile.txt"
string moveTo = "c:\test\test\SomeFile.txt"
if (File.Exists(moveTo))
{
File.Delete(moveTo);
}
File.Move(file, moveTo);
According to the docs for File.Move there is no "overwrite if exists" parameter. You tried to specify the destination folder, but you have to give the full file specification.
Reading the docs again ("providing the option to specify a new file name"), I think, adding a backslash to the destination folder spec may work.
Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.
If you don't have the option to delete the already existing file in the new location, but still need to move and delete from the original location, this renaming trick might work:
string newFileLocation = #"c:\test\Test\SomeFile.txt";
while (File.Exists(newFileLocation)) {
newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
}
File.Move(#"c:\test\SomeFile.txt", newFileLocation);
This assumes the only '.' in the file name is before the extension.
It splits the file in two before the extension, attaches "_copy." in between.
This lets you move the file, but creates a copy if the file already exists or a copy of the copy already exists, or a copy of the copy of the copy exists... ;)
I have the following code which copies a file to a specific folder and then renames it.
When a file with that name already exists I get the following exception:
Cannot create a file when that file already exists
Is there a way to overwrite the file and rename it? or I should delete the old one and then change the name?
Here is my code:
File.Copy(FileLocation, NewFileLocation, true);
//Rename:
File.Move(Path.Combine(NewFileLocation, fileName), Path.Combine(NewFileLocation, "File.txt"));
Try to use only:
if (File.Exists("newfilename"))
{
System.IO.File.Delete("newfilename");
}
System.IO.File.Move("oldfilename", "newfilename");
One simple option is to delete the file if it exists:
if (System.IO.File.Exists(newFile)) System.IO.File.Delete(newFile);
System.IO.File.Move(oldFile, newFile);
Something like that should work.
You're correct, File.Move will throw an IOException if/when the filename already exists. So, to overcome that you can perform a quick check before the move. e.g.
if (File.Exists(destinationFilename))
{
File.Delete(destinationFilename);
}
File.Move(sourceFilename, destinationFilename);
You should use File.Exists rather than letting the Exception throw. You can then handle if the file should be overwrote or renamed.
Step 1 : as a first step identify wether the file exists or not before copying the file.
using File.Exists() method
Step 2: if the file already exists with same name then delete the existing file using File.Delete() method
Step 3: now copy the File into the new Location using File.Copy() method.
Step 4: Rename the newly copied file.
Try This:
string NewFilePath = Path.Combine(NewFileLocation, fileName);
if(File.Exists(NewFilePath))
{
File.Delete(NewFilePath);
}
//Now copy the file first
File.Copy(FileLocation, NewFileLocation, true);
//Now Rename the File
File.Move(NewFilePath, Path.Combine(NewFileLocation, "File.txt"));
I always use MoveFileEx with the flag MOVEFILE_REPLACE_EXISTING.
Limitations:
It needs to use PInvoke, so it means your code will only work on the Windows platform.
This flag MOVEFILE_REPLACE_EXISTING only work with File(Doesn't work with Folder)
If lpNewFileName or lpExistingFileName name a directory and lpExistingFileName exists, an error is reported.
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.
I use Word.Interop to work with Word Document and let user to open a file from hard disk.
Sometimes I get error saying that the file that user has chosen is readonly.
How can I check if a file is readonly or not?
Are you sure you are actually talking about the File attribute (that can be set via the Windows file properties dialog)? If so, you can use FileInfo.IsReadOnly:
FileInfo fileInfo = new FileInfo(#"path\to\file");
if (fileInfo.IsReadOnly)
{
// do something
}
otherwise, refer to this answer if another process is using the file.
I have created a text file to save the error in that created file. I have a button which, once pressed, generates an error which should be saved to the file. But if I press the button twice, it will overwrite the first error generated, because the contents of the file are overwritten. I want to generate a another separate file to save the new error. A new file should be generated for each new error.
Thanks in advance
Simple use: FileExists Method and then if it exists pick a new name. Alternatively you could just append to the file.
PSUDO:
public string checkFileName(string fileName){
if(File.Exists(fileName)){
/Pick a new one
newFileName= fileName + DateTime.Now.ToLongDateString()
return checkFileName(newFileName)
}
return fileName
}
This could be the perfect link for you How to Open and Append a log file
You can add time stamp in filename, in this case you would get new file each time.
private void SaveErrorMessage(string errorMessage)
{
string errorFile = null;
for( int x = 0; x < Int32.MaxValue; ++x )
{
errorFile = string.Format(CultureInfo.InvariantCulture, "error-{0}.txt", x);
if( !System.IO.File.Exists(errorFileTest) )
{
break;
}
}
File.WriteAllText(errorFile, errorMessage);
}
This will overwrite the last file after you've had Int32.MaxValue files, but that'll take a while.
An alternative (and probably better) approach would be to simply append to the file, rather than creating a new one.
You may also want to consider using a more robust logging solution, such as log4net.
Creating file in C# is probably what you're looking for.
So you want to generate a unique file name for each error that occurs in your program? Probably the easiest way to accomplish this is to use the date/time when the error occured to name the file. In the function where you are writing to the file you will want to name the file like this:
string filename = LogPath + DateTime.Now.ToString("yyyyMMdd.HHmmss") + ".err";
Where LogPath is the path to the folder you want to write the error files to.