I'm making an application, and at some point it does the following: Checks if a file that will be created, already exists in a directory (output), if it exists, he sends for the Errors folder, if not, it sends to the output folder. But comes a point where the program transfers the file to the folder errors, and buga, saying that the file does not exist, for example, he just transfer it t file (49) .png, and he again read the same file ! Funny is only in some cases it
if (System.IO.File.Exists(entrada + "t (" + i + ").png")){
string[] datas1 = Spire.Barcode.BarcodeScanner.Scan(#"C:\\QTRACK\\Entrada\\PNG\\t (" + i + ").png");
this.textBox1.Text = datas1[0];
foreach (string code in datas1)
{
DirectoryInfo exit = new DirectoryInfo(#"C:/QTRACK/Erro/");
FileInfo[] teste = exit.GetFiles("*.png");
x = teste.Length +1;
for (c = x; c <= 1000000000; c++)
{
if (System.IO.File.Exists(saida + code + ".png"))
{
System.IO.File.Move(entrada.ToString() + "t (" + i + ").png", erro + "e" + c + ".png");
}
else
{
System.IO.File.Move(entrada.ToString() + "t(" + i + ").png", saida + code + ".png");
}
}
}
}
else
{
}
}
}
It gives the error FileNotFoundExecption, however, was himself who changed the file and're trying to change again. Please help.
Related
Here is all I want to do: Every time the button is clicked, an openfile dialog is opened, the user clicks on a picture, then this picture is copied to a specific folder and renamed to a number. Every picture's name in this folder should be a number, but they must all be different. My code so far:
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
int i = 0;
if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
MessageBox.Show(picturedir + "\\" + i.ToString() + ".png" + ".....Already Exists.");
}
else if (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == false)
{
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Of course here, the first picture is copied and renamed to "0.png" but the next pictures are not copied at all, because the "if" gives true. Any ideas ? Thanks.
You could do this:
...
int i = 0;
while (System.IO.File.Exists(picturedir + "\\" + i.ToString() + ".png") == true)
{
i++;
// I wouldn't show that message each time, gonna get pretty old for lots of pics!
}
System.IO.File.Copy(openfile.FileName, picturedir + "\\" + i.ToString() + ".png", true);
...
If you want the next number, you can enumerate the existing files, find the maximum number now in use and add 1. Something like:
var files = Directory.EnumerateFiles(myCurrentDirectory, "*.png");
var fileNumStrings = from file in files select Path.GetFileNameWithoutExtension(file);
var max = 0;
foreach (var fileNumString in fileNumStrings)
{
if (int.TryParse(fileNumString, out var filenum))
{
if (filenum > max)
{
max = filenum;
}
}
}
var nextNum = max + 1;
I am a new to c# and i am doing a window form program that to check the excel file is exist or not. If exists then need to verify the excel file is damaged or not , but i have no idea how to write the code . the part of searching excel file i had done .
#
int point = 0;
if (File.Exists(path1[0]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Tranfser Error");
point = 1;
}
else
{
for (int x = 1; x < path1.Length; x++)
{
if (File.Exists(path1[x]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Error");
point = 1;
}
}
}
if (File.Exists(path2[0]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Successful");
point = 1;
}
else
{
for (int x = 1; x < path2.Length; x++)
{
if (File.Exists(path2[x]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Successful");
point = 1;
}
}
}
if (File.Exists(path3))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Havent Transfer");
point = 1;
}
if (point == 0)
{
MessageBox.Show("No File of the date "+ Year +"-"+ Month +"-"+ Day);
}
Looks like you need to check multiple paths for existence and file format? if so please construct your code better way. However the below function shall give you expected result. This uses EPPlus library, install it through nuget.
enum ExcelFileTestResult
{
FileNotFound,
ValidFormat, //File found, valid excel
InvalidFormat //File found but not valid excel
}
public static ExcelFileTestResult CheckExcelFile(string path)
{
ExcelFileTestResult result = ExcelFileTestResult.FileNotFound;
if (File.Exists(path))
{
FileInfo fi = new FileInfo(path);
try
{
// Trying to read file using EPPlus
// if the file is not valid format, it will throw error
using (ExcelPackage p = new ExcelPackage(fi))
{
result = ExcelFileTestResult.ValidFormat;
}
}
catch (InvalidDataException ex)
{
result = ExcelFileTestResult.InvalidFormat;
}
}
return result;
}
Note: EPPlus works only for xlsx, not xls.
https://github.com/JanKallman/EPPlus
i know this seems pretty simple and i know theres other questions asking this but i just need to know what im personally doing wrong and why it doesnt work because it should.
int ImageCounter = 1;
foreach (var Image in ImageFilePaths)
{
{
// Console.WriteLine(Image);
// Console.WriteLine(RenameFolderPath + #"\" + ImageCounter + ".jpeg");
File.Move(Image, RenameFolderPath + #"\" + ImageCounter + ".jpeg");
ImageCounter++;
}
}
So theres about 150 images in a folder and after running this, im left with 11, 10 of which are numbered 1-10 and the 11th is left with its original name.
if i print (image) it will print about 150 of the original names, if i print the 2nd writeline, it will print the exact same but "1 - about 150" instead of the original name. so theres no problems there, it must be with the file.move but i cannot see anything wrong
Not sure what the rest of your code looks like, but this works for me:
void Main()
{
MoveFiles(#"c:\Temp\MoveTest", #"C:\Temp\MoveTest1");
}
public void MoveFiles(string fromDir, string toDir)
{
int ImageCounter = 1;
// Take a snapshot of the file system.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(fromDir);
IEnumerable<System.IO.FileInfo> ImageFilePaths = dir.GetFiles("*.*", System.IO.SearchOption.TopDirectoryOnly);
foreach (var Image in ImageFilePaths)
{
{
Console.WriteLine(Image);
Console.WriteLine(toDir + #"\" + ImageCounter + ".jpeg");
File.Move(Image.FullName, toDir + #"\" + ImageCounter + ".jpeg");
ImageCounter++;
}
}
}
With my filesystemwatcher I check when a file needs to be copied to a 2nd directory. Everytime. So for example I put in test.txt in dir1 and it automatically copies or cuts the file to dir2. Now when I put in test2.txt in dir1, nothing happens. Why is nothing happening the 2nd time?
Edit: It's a Windows Service
Here is my code:
private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
variable_reset();
cut_copy = ConfigurationManager.AppSettings[#"cut"];
logger("File created> " + e.FullPath + " -Date:" + DateTime.Now);
filepath = Path.Combine(source, e.Name);
name = Path.GetFileNameWithoutExtension(filepath);
extension = Path.GetExtension(e.FullPath);
size = e.Name.Length;
strSelectCmd = "INSERT INTO files (name,size,last_edit,extension) VALUES('" + name + "','" + size + "',now(),'" + extension + "')";
readquery = "select * from files where name='" + name + "'";
Mysql();
postgresql();
Record();
if (string.IsNullOrEmpty(filename) == false)
{
if (Directory.Exists(e.FullPath))
{
copyfolder();
Directory.CreateDirectory(target);
}
else
{
if (WaitForFileAvailable(e.FullPath, TimeSpan.FromSeconds(10)))
{
var file = Path.Combine(source, e.Name);
var copy_file = Path.Combine(target, e.Name);
var destination = Path.Combine(target, Path.ChangeExtension(source, Path.GetExtension(source)));
if ((String.Compare(cut_copy, "cut"))==0)
{
if (File.Exists(file))// Check to see if the file exists.
{ //If it does delete the file in the target and copy the one from the source to the target.
File.Delete(copy_file);
}
File.Move(e.FullPath, Path.Combine(target, e.Name));
}
if ((String.Compare(cut_copy, "copy"))==0)
{
if (File.Exists(file))// Check to see if the file exists.
{ //If it does delete the file in the target and copy the one from the source to the target.
File.Delete(copy_file);
}
File.Copy(e.FullPath, Path.Combine(target, e.Name));
}
}
else // The file failed to become available within 10 seconds.
{
logger("Copy has failed reason: File is being used by another program");
}
}
}
else
{
query = "INSERT INTO files (name,size,last_edit,extension) VALUES('" + name + "','" + size + "',now(),'" + extension + "')";
Mysql();
}
}
I have found many posts on checking if the file on the ftp server exists. None of the codes provided helped. I am trying to auto upload small files to the ftp server BUT I don't want to override the file if it already exists. The following code works if the file already exists but if it doesn't it kicks back an error and does not run the code in the if statement.
System.Console.WriteLine("check if hash file is on ftp server " + hashfile);
string fileSize = ftpClient.getFileSize(hashfile);
int fSize =-1;
bool res = (Int32.TryParse(fileSize, out fSize));
if (res)
{
System.Console.WriteLine("Hash file is not on ftp server " + hashfile);
ftpClient.upload(hashfile, #hashfile);
ftpClient.upload(charfile, #charfile);
File.Delete(hashfile);
File.Delete(charfile);
}
else
{
System.Console.WriteLine("Hash file is on ftp server " + hashfile);
string newHashFile = "ntlmhash" + str_cint + "_" + str_pint + "_" + e + ".txt";
while (File.Exists(newHashFile))
{
e++;
newHashFile = "ntlmhash" + str_cint + "_" + str_pint + "_" + e + ".txt";
string FileSize = ftpClient.getFileSize(newHashFile);
int FSize =-1;
if (Int32.TryParse(FileSize, out FSize))
{
ftpClient.upload(newHashFile, #newHashFile);
ftpClient.upload(charfile, #charfile);
File.Delete(newHashFile);
File.Delete(charfile);
}
else
{
e++;
}
}
System.IO.File.Move(hashfile, newHashFile);
ftpClient.upload(newHashFile, #newHashFile);
ftpClient.upload(charfile, #charfile);
File.Delete(newHashFile);
File.Delete(charfile);
}