One of my executable process produces two files. I want to move one file that is produced to shared drive. I am writing an automatic process to move the file from one location to shared drive. The only issue is file name changes every time the executable is run so I don't have the exact filename with me. I only have the extension, .xls. I have only one .xls file in my directory.
I tried doing this
File.Copy(#"*.xls", #"\\serv44\Application\testing\name\test2\*.xls", true);
It threw an error saying Invalid name. After moving the file to shared drive. I want to delete the .xls file.
File.Delete("*.xls");
any help will be appreciated
You should get file name and then do whatever you want with that file. I.e. if you have only one xls file in the source directory:
var targetDirectory = #"\\serv44\Application\testing\name\test2\";
var sourceFile = Directory.EnumerateFiles(sourceDirectory, "*.xls").FirstOrDefault();
if (sourceFile != null)
{
var sourceFileName = Path.GetFileName(sourceFile);
var targetFileName = Path.Combine(targetDirectory, sourceFileName);
File.Copy(sourceFileName, targetFileName);
File.Delete(sourceFileName);
}
Note: instead of copy and delete you can use single Move operation.
If you want to move several files from your source directory, then instead of taking first one process all found files in a loop:
foreach(var sourceFile in Directory.EnumerateFiles(sourceDirectory, "*.xls"))
{
var sourceFileName = Path.GetFileName(sourceFile);
var targetFileName = Path.Combine(targetDirectory, sourceFileName);
File.Move(sourceFileName, targetFileName);
}
This should give you that file name:
var fileName = Directory.GetFiles(yourDirectory, "*.xls").ToList().FirstOrDefault();
Related
We get an excel file in a specific location where the name of the file may vary every time.
So every time we rename the excel file manually to "Report.xlsx" and then we have some operation to be done using a script task. The file_Path + file_Name is hardcoded in the script task as
Microsoft.Office.Interop.Excel.Workbook workBook = excelApp.Workbooks.Open(#"D:\Desktop\Report.xlsx");
Is there a way to get the file name from the file location and pass it to the above code ?
Note:
The file Path is static but the file name will vary every time.
At a time there will be only one excel file in the file Path.
We are already using a Sequence Container so cant change it.
Thanks in advance..
This will let you use the actual file name. Make sure to reference System.Linq
var dir = new System.IO.DirectoryInfo(#"D:\Desktop");
var fullFilePath = dir.GetFiles("*.xlsx").Select(f => f.FullName).First();
if(fullFilePath != null)
Microsoft.Office.Interop.Excel.Workbook workBook = excelApp.Workbooks.Open(fullFilePath);
I'm trying to move a file from the desktop to a directory called "Textfiles" but every time I try to it gives me this error.
Additional information: The target file "C:\Users\Developer\Documents\Textfiles" is a directory, not a file.
Now I know that using
File.Copy(fileName, targetPath);
Would be wrong and that's what I am using right now, It takes two parameters, the first being the file yopu want to copy and the second one being the file it's replacing? Correct me if i am wrong on the second parameter.
Anyways, I tried System.IO.Directory.Move(fileName, destFile); aswell but that pretty much gave me the same error.
The two parameters are very simple, just two string that consists of paths.
string fileName = filePath.ToString();
string targetPath = #"C:\Users\Developer\Documents\Textfiles";
What would be the correct way to transfer fileName to targetPath ?
You need to specify the destination filename.
string fileOnly = System.IO.Path.GetFileName(fileName);
string targetPath = System.IO.Path.Combine(#"C:\Users\Developer\Documents\Textfiles", fileOnly);
System.IO.File.Move(fileName, targetPath);
See https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
for documentation:
destFileName
Type: System.String
The name of the destination file. This cannot be a directory or an existing file.
You have to add the new file name to the destination directory.
You can get the file name with:
result = Path.GetFileName(fileName);
thus in your case:
string targetPath = #"C:\Users\Developer\Documents\Textfiles\" + Path.GetFileName(fileName);
I'm experiencing a strange issue here and not quite sure what I'm missing. I ran the code below and it did create a .zip file and I watched the size increase from 0KB to 8,992KB. However, as I open the .zip file, I don't see any file. And if I try to "Extract All..." from explorer, it shows "Windows can not complete the extraction" because the .zip file "is invalid". Any idea what I did wrong?
if (File.Exists(ZipName))
File.Delete(ZipName);
using (ZipArchive archive = ZipFile.Open(ZipName, ZipArchiveMode.Create))
{
foreach (string sFileName in FileNames)
{
archive.CreateEntryFromFile(sFileName,sFileName,CompressionLevel.Optimal);
}
}
You need to strip the drive letter from the entryName, which is the 3rd parameter to CreateEntryFromFile().
So instead of
archive.CreateEntryFromFile(sFileName, sFileName, CompressionLevel.Optimal);
Use
archive.CreateEntryFromFile(sFileName, sFileName.Substring(3), CompressionLevel.Optimal);
I ran into the same problem, and I discovered a solution. It turns out that I was feeding the method a full path to the file for both filename arguments, like so:
// This gets a list of files with their full paths
var fileList = Directory.GetFiles(_outputDir, "*.txt");
foreach (var file in fileList)
{
archive.CreateEntryFromFile(file, file, CompressionLevel.Optimal);
}
That gave me the same problem you had -- an empty zip file, which was invalid. (By the say, my file paths weren't that long -- they were C:\Results\[some_guid].txt.)
The solution was to get the files as FileInfo objects, then for the first argument use the full path and for the second argument just use the file name, like so:
// This gets a set of FileInfo objects, with a FullName property that is
// the full path to the file, and a Name property that is just the file name.
var directoryInfo = new DirectoryInfo(_outputDir);
var fileList = directoryInfo.GetFiles("*.txt");
foreach (var file in fileList)
{
archive.CreateEntryFromFile(file.FullName, file.Name, CompressionLevel.Optimal);
}
This ended up working perfectly. If I opened the zip file, the files were there. If I extracted it, the extraction worked and the files seemed to be valid.
I was trying to move a file from my Resx to my PC, but I'm keep having problems.
So I import a folder named "bad" in the Resources and I use the File.Move method to move the folder "bad" into my PC.
But the program keeps crashing because it says: Cannot create a file when its already exists.
Here the code I use:
//txtpath is the root folder. I let the user choose the root folder and save it in txtpath.text
private void btnbadname_Click(object sender, EventArgs e)
{
string source = "Resources\bad";
string destination = txtpath.Text + #"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App";
File.Move(source, destination);
MessageBox.Show("脏话ID已开启, 教程请点击下面的链接");
}
The destination Directory cannot exist. In your code you are creating the Directory if it doesn't exist and then trying to move your directory, the Move Method will create the directory for you. If the Directory already exists you will need to Delete it or Move it.
See:
Cannot create a file when that file already exists when using Directory.Move
Destination supposed to have the filename as well
string destination = txtpath.Text + #"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App\yourfilename.ext";
You are using File.Move to move directory, why not using Directory.Move.
The MSDN documentation will only move files from a source to a destination, while Directory.Move will move the directory itself.
If I misunderstood you, and you want to move a file;
You can check if the file exists before or not using something like:
if(File.Exists(fileName))
File.Delete(fileName);
Edit:
If you want to iterate through the directory and make sure that the file doesn't exist before moving it, you can use something like:
//Set the location of your directories
string sourceDirectory = #"";
string destDirectory = #"";
//Check if the directory exists, and if not create it
if (!Directory.Exists(destDirectory))
Directory.CreateDirectory(destDirectory);
DirectoryInfo sourceDirInfo = new DirectoryInfo(sourceDirectory);
//Iterate through directory and check the existance of each file
foreach (FileInfo sourceFileInfo in sourceDirInfo.GetFiles())
{
string fileName = sourceFileInfo.Name;
string destFile = Path.Combine(destDirectory, fileName);
if (File.Exists(destFile))
File.Delete(destFile);
//Finally move the file
File.Move(sourceFileInfo.FullName, destFile);
}
When using MoveTo, provide the full path of where you are sending the file, including the file name, eg, pic123.jpg. If you use DirectoryInfo to get an array of files and want to move any of them, append the Name property of the file to the directory path where you are sending the file.
imgFile.MoveTo("C:\myPictures\ArchiveFolder\pic123.jpg")
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);
}