check file on ftp server - c#

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);
}

Related

Delete file which cannot delete because is used by another process

I know you are going to tell me that this question is stupid but I really cannot find a solution to delete my file.
In fact, I open a connection to an .add file (same style as SQL in a way) but afterwards I cannot delete it because it is used by another process which is the process of my application.
While doing some research on the internet I was able to find the solution to kill the process however if I do this it stops my application. Then I also found the GC collect but it doesn't work : /
There is my code :
try
{
string idClient = "parfilux";
string tableName = "ACT,ACF";
string dataSourceDBF = "C:/winbooks/data/parfilux";
string path = dataSourceDBF ;
string pathTemp = dataSourceDBF + "/CopyTempWebService/";
if (!Directory.Exists(pathTemp)) Directory.CreateDirectory(pathTemp);
string addFile = path + "/" + idClient + ".add";
File.Copy(addFile, pathTemp + idClient.ToUpper() + ".add");
File.Copy(addFile.Replace(".add", ".ai"), pathTemp + "/" + idClient.ToUpper() + ".ai");
File.Copy(addFile.Replace(".add", ".am"), pathTemp + "/" + idClient.ToUpper() + ".am");
tableName = tableName.Replace(" ", "");
string[] tables = tableName.Split(',');
string pathTable = null;
foreach (string tab in tables)
{
pathTable = path + "/" + idClient.ToUpper() + "_" + tab.ToUpper() + ".dbf";
File.Copy(pathTable, pathTemp + idClient.ToUpper() + "_" + tab.ToUpper() + ".dbf");
File.Copy(pathTable.Replace(".dbf", ".cdx"), pathTemp + idClient.ToUpper() + "_" + tab.ToUpper() + ".cdx");
}
AdsConnection dbfCo;
//dbfCo.Close();
dbfCo = new AdsConnection(#"data Source=" + dataSourceDBF + "/CopyTempWebService/" + idClient + ".add;User ID=admin;Password=;ServerType=Local;ReadOnly=true;pooling=true;TrimTrailingSpaces=true;ShowDeleted=TRUE;TableType=CDX;LockMode=COMPATIBLE");
dbfCo.Open();
//QueryDataDBF(tableName, idClient, false);
dbfCo.Close();
dbfCo.Dispose();
//Process process = Process.GetCurrentProcess();
//Console.WriteLine(process.MainModule);
//process.Kill();
//foreach(Process pro in process)
//{
// Console.WriteLine(pro);
// if(pro.ProcessName == pathTemp + idClient.ToUpper() + ".add")
// {
// pro.Kill();
// }
//}
//System.GC.Collect();
//System.GC.WaitForPendingFinalizers();
//File.Delete(pathTemp + idClient.ToUpper() + ".add");
Directory.Delete(dataSourceDBF + "/CopyTempWebService", true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
I open a connection to my .add with the Advantage Data Provider library.
Do you have any idea to fix this problem ? thank you in advance ;)

How to add local file link to Exported CSV file using C#

I want to add the link to my local file into one of the columns of Exported CSV file.So that when user clicks on the link the local file open. I have searched the internet for this but can't find any good solution.
Here is the screenshot of what i try to do -
Suppose when user clicks on File path selected row file full name then upon click i should open the file at that localtion.
My code to generate the CSV file is-
public void GetExportDetailsCSV(ExportInformation ExportInfo)
{
StringBuilder cameraRows = new StringBuilder();
string filePath = ExportInfo.ExportOutputPathAtClient + SLASH_STRING + "ExportDetails.csv";
string columnsNames = "File Name ,File Path" + "\r\n";
if(Directory.Exists(ExportInfo.ExportOutputPathAtClient))
{
try
{
foreach (string newPath in Directory.GetFiles(string.Format("{0}{1}", ExportInfo.ExportOutputPathAtClient, SLASH_STRING), "*" + ExportInfo.VideoFileFormat.ToString(), SearchOption.AllDirectories))
{
FileInfo FileDetails = new FileInfo(newPath);
cameraRows.Append(string.Format("{0},{1}\r\n", FileDetails.Name, FileDetails.FullName));
}
string FinalData = "\nExport Remarks : Simple Export " + "\n\n" + "," + "," + "," + "," + "File Details" + "," + "\r\n" + "\r\n" + columnsNames + "\n " + cameraRows;
using (var stream = System.IO.File.CreateText(filePath))
{
stream.WriteLine(FinalData);
}
}
catch(Exception ex)
{
}
}
}
My question is simple how can i put file location value as a link in my Exported CSV file.
Thankyou!
Try using the Hyperlink function. Check this link
You can try this sample. Open notepad type below the line and save it as CSV.
This,is,demo,"=HYPERLINK(""http://www.google.com/"",""Link"")"
Hopefully, this will solve the problem.

Permissions on a folder

I have been looking for some time now and have not been able to find this. How can I set my program up to write or update a file from multiple users but only one group is allowed to open the read what is in the folder?
class Log_File
{
string LogFileDirectory = #"\\server\boiseit$\TechDocs\Headset Tracker\Weekly Charges\Log\Log Files";
string PathToXMLFile = #"\\server\boiseit$\scripts\Mikes Projects\Headset-tracker\config\Config.xml";
string AdditionToLogFile = #"\Who.Did.It_" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Year + ".txt";
XML XMLFile = new XML();
public void ConfigCheck()
{
if (!File.Exists(PathToXMLFile))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
}
}
public void CreateLogFile()
{
if (Directory.GetFiles(LogFileDirectory).Count() == 0)
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
else if (!File.Exists(XMLFile.readingXML(PathToXMLFile)))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
else
{
FileInfo dateOfLastLogFile = new FileInfo(XMLFile.readingXML(PathToXMLFile));
DateTime dateOfCreation = dateOfLastLogFile.CreationTime;
if (dateOfLastLogFile.CreationTime <= DateTime.Now.AddMonths(-1))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
}
}
public void CreateFileOrAppend(string whoDidIt)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetStore((IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly | IsolatedStorageScope.User), null, null))
{
using (StreamWriter myWriter = new StreamWriter(XMLFile.readingXML(PathToXMLFile), true))
{
if (whoDidIt == "")
{
}
else
{
myWriter.WriteLine(whoDidIt);
}
}
}
}
This is my path where it needs to go. I have the special permission to open and write to the folder but my co workers do not. I am not allow to let them have this permission.
If I where to set up a database how would i change this code
LoggedFile.CreateFileOrAppend(Environment.UserName.ToUpper() + "-" + Environment.NewLine + "Replacement Headset To: " + AgentName + Environment.NewLine + "Old Headset Number: " + myDatabase.oldNumber + Environment.NewLine + "New Headset Number: " + HSNumber + Environment.NewLine + "Date: " + DateTime.Now.ToShortDateString() + Environment.NewLine);
I need it to pull current user, the agents name that is being affected the old headset and the new headset, and the time it took place.
While you create file, you have to set access rules to achieve your requirements. .
File.SetAccessControl(string,FileSecurity)
The below link has example
https://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol(v=vs.110).aspx
Also the "FileSecurity" class object, which is an input parameter, has functions to set access rules, including group level control.
Below link has example
https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesecurity(v=vs.110).aspx
This question will be opened under a new question since I am going to take a different route for recording the data I need Thank you all for the help

File transfer error

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.

File upload control error

im using a file upload control and here is my code :
//Uploading the image
if (imageUpload.HasFile)
{
try
{
if (imageUpload.PostedFile.ContentType == "image/jpeg")
{
if (imageUpload.PostedFile.ContentLength < 102400)
{
string im = ( "~/User" + "/" + Page.User.Identity.Name + "/" + Page.User.Identity.Name + ".jpeg");
imageUpload.SaveAs(im);
uploadLabel.Text = "";
}
else
{
uploadLabel.Text = "File size must be less than 1024 kb";
}
}
else
{
uploadLabel.Text = "File must be in jpeg/jpg format";
}
}
catch(Exception ex)
{
uploadLabel.Text = "File upload failed becuase: " + ex.Message;
}
}
but im getting an error:
The SaveAs method is configured to require a rooted path, and the path "path" is not rooted.
what am i doing wrong.
thanks
SaveAs() requires an absolute path.
try using Request.PhysicalApplicationPath + "\\User"
The Save method is configured to require an absolute path (starting with X:\..., in some drive).
You should call Server.MapPath to get the absolute path on disk to ~/whatever.
Add Server.MapPath where you declare im
Server.MapPath gives you the absolute path.
string im = Server.MapPath("/User") + "/" + Page.User.Identity.Name + "/" + Page.User.Identity.Name + ".jpeg";
string filename = FileUpload1.FileName.ToString();
if (filename != "")
{
ImageName = FileUpload1.FileName.ToString();
ImagePath = Server.MapPath("Images");
SaveLocation = ImagePath + "\\" + ImageName;
SaveLocation1 = "~/Image/" + ImageName;
sl1 = "Images/" + ImageName;
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
try this may be help ful.......

Categories

Resources