Problems uploading files using Chilkat - c#

I am trying to upload a file to a Server using sftp. I have downloaded and installed Chilkat and i am downloading files without any issues. But when i try to upload files to the server, i get no error stating that the uploading files. When i check for response messages, it says "file upload success 1" and one is true But the files doesn't get uploaded to the server.
this is my code:
public void UploadAndMoveFile()
{
bool success = false;
string path = #"\\geodis\";
string archive = #"\\Archive\";
string[] files = Directory.GetFiles(path);
if (files.Count() == 0)
{
//no files
}
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
string fileSource = path + fileName;
string fileDestination = archive + fileName;
string handle;
string ftp = #"\IN\"+fileName;
handle = sftp.OpenFile(ftp, "writeOnly", "createTruncate");
if (handle == null)
{
Console.WriteLine(sftp.LastErrorText);
return;
}
success = sftp.UploadFile(handle, fileSource);
if (success == true)
{
AppendLogFile("Uploading File Succeeded", "Uploade File", fileName);
System.IO.File.Move(fileSource, fileDestination);
AppendLogFile("Moving File Succeeded", "Moving File", fileName);
}
else
{
// no files
}
}
}
Can anyone help me find out what I am doing wrong?

Found the Issue, in the upload method i had handle variable instead of the ftp variable.
here is the solution:
public void UploadAndMoveFile()
{
bool success = false;
string path = #"\\geodis\";
string archive = #"\\Archive\";
string[] files = Directory.GetFiles(path);
if (files.Count() == 0)
{
//no files
}
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
string fileSource = path + fileName;
string fileDestination = archive + fileName;
string handle;
string ftp = #"\IN\"+fileName;
handle = sftp.OpenFile(ftp, "writeOnly", "createTruncate");
if (handle == null)
{
Console.WriteLine(sftp.LastErrorText);
return;
}
success = sftp.UploadFile(ftp, fileSource);
if (success == true)
{
AppendLogFile("Uploading File Succeeded", "Uploade File", fileName);
System.IO.File.Move(fileSource, fileDestination);
AppendLogFile("Moving File Succeeded", "Moving File", fileName);
}
else
{
// no files
}
}
}

Related

Get xslx and xls file from a folder and copy it in another folder

I want to download both xlsx and xls file from a folder using c#.I have tried below way:
foreach (DriveInfo mydrive in mydrives)
{
if (mydrive.DriveType != DriveType.Removable)
{
if (mydrive.DriveType == DriveType.CDRom)
{
}
if (mydrive.DriveType != DriveType.CDRom)
{
var sourceDirectory = mydrive.Name;
string[] files = System.IO.Directory.GetFiles(sourceDirectory, "*xlsx");
foreach (var txtfiles in files)
{
string sourceFile = txtfiles;
string filename = null;
filename = Path.GetFileName(sourceFile);
string destinationFile = #"E:\Prog\" + filename;
File.Copy(sourceFile, destinationFile, true);
}
}
}
}
my code only fetches xlsx file i need both xlsx and xls file.
Try changing
string[] files = System.IO.Directory.GetFiles(sourceDirectory, "*xlsx");
To
string[] files = System.IO.Directory.GetFiles(sourceDirectory, "*.xls");
This will match any file that ends in .xls or .xlsx in sourceDirectory.

how to upload entire folder with exact folder structure?

I am uploading an entire folder to a server.
The folder contains files and subfolders in it.
I want it to be exactly uploaded as it is in my local machine.
I tried it with FolderBrowserDialog and then the folder copying logic.
It works well on local machine but after deployment I am getting Unhandled exception.
Context: Section1
try
{var t = new Thread((ThreadStart)(() =>
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
//foreach (var path in Directory.GetFiles(fbd.SelectedPath))
//{
// //Console.WriteLine(path); // full path
// //Console.WriteLine(System.IO.Path.GetFileName(path)); // file name
//}
}
else
{
}
//fbd.RootFolder = System.Environment.SpecialFolder.MyComputer;
//fbd.ShowNewFolderButton = true;
//if (fbd.ShowDialog() == DialogResult.Cancel)
// return;
selectedPath = fbd.SelectedPath;
}));
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
// ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup();", true);
FilesBulkUpload(selectedPath);
private void FilesBulkUpload(string path)
{ try
{ if (path != null)
{
string lastFolderName = Path.GetFileName(path);
Copyfolder(path, #"D:\Sneha\test\" + lastFolderName,true);
MessageBox.Show("Folder Uploaded Successfully");
}
}
catch (Exception ex)
{
LogError(ex);
}
}
Copyfolder logic:
if (Directory.Exists(SourcePath))
{
if (Directory.Exists(DestinationPath) == false)
Directory.CreateDirectory(DestinationPath);
foreach (string fls in Directory.GetFiles(SourcePath))
{ FileInfo flinfo = new FileInfo(fls);
string ext = flinfo.Extension;
if (ext`enter code here` == ".exe" || ext == ".zip")
{
MessageBox.Show("Please exclude files like with .exe, .zip extension");
}
else
{
flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
}
}
foreach (string drs in Directory.GetDirectories(SourcePath))
{
DirectoryInfo diDi = new DirectoryInfo(drs);

convert a jpg/png/txt or any file format to pdf using mvc5

How do i convert a jpg/png/txt or any file format to pdf using mvc c#.
Here is the code:
public ActionResult SaveProfileDocument(string code)
{
bool isSavedSuccessfully = true;
string fName = "";
string _documentname = String.Empty;
try
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Documents\\Profile\\" + code, Server.MapPath(#"\")));
string pathString = System.IO.Path.Combine(originalDirectory.ToString());
var fileName1 = Path.GetFileName(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists)
System.IO.Directory.CreateDirectory(pathString);
_documentname=fName;
var path = string.Format("{0}\\{1}", pathString, file.FileName);
if (System.IO.File.Exists(path)) {
_documentname=Guid.NewGuid()+"_"+file.FileName;
var path2 = string.Format("{0}\\{1}", pathString,_documentname );
file.SaveAs(path2);
}
else {
file.SaveAs(path);
}
}
}
}
catch (Exception ex)
{
isSavedSuccessfully = false;
}
if (isSavedSuccessfully)
{
return Json(new { Message = fName, documentname = _documentname });
}
else
{
return Json(new { Message = "Error in saving file", documentname=""});
}
}
In the above code i am saving the file.but
here i need to convert the file and then save.
so for convert i need a separate class or method here only call that method.
The thing is that while upload a file inthat time need to convert pdf any file to convert pdf. and save in folder or whatever.
can't convert an image file to PDF. You can create a PDF file and add the image file to it:
string pdfpath = Server.MapPath("PDFs");
string imagepath = Server.MapPath("Images");
Document doc = new Document();
try
{
PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Images.pdf", FileMode.Create));
doc.Open();
doc.Add(new Paragraph("GIF"));
Image gif = Image.GetInstance(imagepath + "/mikesdotnetting.gif");
doc.Add(gif);
}
catch (Exception ex)
{
//Log error;
}
finally
{
doc.Close();
}
here i am refer:
https://www.mikesdotnetting.com/article/87/itextsharp-working-with-images

Downloading .mp3 file from the server and load in MediaPlayer

I want to download a .mp3 file from the localhost server, but the only problem I think is the directory that I am downloading to. Code is not giving any errors but in if(file.Exists()) is always returning false, it seems that the file is not properly downloaded.
Downloading the file:
if (isConnectedToInternet())
{
using (var client = new WebClient())
{
int numberFile = 1;
ProgressDialog pd = new ProgressDialog(Activity);
pd.SetCancelable(true);
pd.SetMessage("Pleasy wait for files to be downloaded... 0/16");
pd.Show();
client.DownloadFileCompleted += (o, s) => {
Toast.MakeText(Activity, "Download file completed.", ToastLength.Long).Show();
};
try
{
client.DownloadFileCompleted += (o, s) => {
if (numberFile == 1)
{
pd.Cancel();
}
};
string appDataDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
string filePath = soundListViewAdapter.GetItemAtPosition(e.Position).path1;
if (!Directory.Exists(appDataDir))
{
Directory.CreateDirectory(appDataDir);
}
//I have to do .Remove(0,1) because filePath starts with the '/'
string path = Path.Combine(appDataDir, filePath.Remove(0, 1));
Toast.MakeText(Activity, path, ToastLength.Long).Show();
System.Uri url = new System.Uri(server + "rpad/api" + soundListViewAdapter.GetItemAtPosition(e.Position).path1);
client.DownloadFileAsync(url, path);
}
catch
{
Toast.MakeText(Activity, "Files are not downloaded", ToastLength.Long);
}
}
}
else
{
Toast.MakeText(Activity, "No connection", ToastLength.Long).Show();
}
Loading the file:
m1 = new MediaPlayer();
string appDataDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
string filePath = prefs.GetString("path1", "empty");
string path = Path.Combine(appDataDir, filePath.Remove(0, 1));
Java.IO.File file = new Java.IO.File(path);
if (file.Exists())
{
FileInputStream fileStream = new FileInputStream(file);
m1.SetDataSource(fileStream.FD);
m1.Prepare();
m1.Start();
}
Code is not giving any errors but in if(file.Exists()) is always returning false, it seems that the file is not properly downloaded.
By Java.IO.File file = new Java.IO.File(path);, you are only creating a File instance. The file hasn't been created on the device. You need to call File.CreateNewFile to create this file, and before that, make sure all the parent folders are created by using Directory.CreateDirectory:
string appDataDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
string filePath = "Test/empty/abc.txt";
string parentPath = Path.Combine(appDataDir, "Test/empty");
string path = Path.Combine(appDataDir, filePath);
Java.IO.File file = new Java.IO.File(path);
Directory.CreateDirectory(parentPath);//make sure the parent directory is created
file.CreateNewFile();//create the file
if (file.Exists())
{
...
}

Delete files after upload and processing from the same location using Directory.Delete() giving error 'Directory is not empty' in c#.net

I am using Zetalongpath to access pdf files for long path.
Files will be uploaded from the location like 'D:\Active Folder\ReadyTobeTransfer\ABC\XYZ' to 'D:\Upload Intake\ABC\XYZ'
i want to delete folder ABC recursively after successful upload, as this is the requirement of client.
here is my code to save the uploaded files from browser.
var FilingDocs = new List<HttpPostedFileBase>();
for (var i = 0; i < Request.Files.Count; i++)
{
if (Request.Files[i].FileName.Substring(Request.Files[i].FileName.LastIndexOf('.') + 1).ToLower() == "pdf")
{
FilingDocs.Add(Request.Files[i]);
}
}
foreach (HttpPostedFileBase file in FilingDocs)
{
if (file != null)
{
// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);
string fileName;
if (file.FileName.LastIndexOf('\\') > 0)
{
fileName = file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1);
}
else
{
fileName = file.FileName;
}
ZlpIOHelper.WriteAllBytes(fullPath + '\\' + fileName, binData);
file.InputStream.Close();
b.Close();
}
}
//DB insert method
//Code to delete Uploaded folder
string ParentFolder = "D:\Active Folder\ReadyTobeTransfer\ABC";
string ChildFolder = "D:\Active Folder\ReadyTobeTransfer\ABC\XYZ";
//Delete Files from ChildFolder
string[] files = Directory.GetFiles(ChildFolder, "*.pdf");
try
{
foreach (string file in files)
{
//Remove read only access
System.IO.File.SetAttributes(file, FileAttributes.Normal);
System.IO.File.Delete(file);
}
//Sleep for 5 second
System.Threading.Thread.Sleep(new TimeSpan(0, 0, 5));
//Check whether Child Folder Exist
if (ZlpIOHelper.DirectoryExists(ChildFolder))
{
//Delete Uploaded Files Folder
Directory.Delete(ChildFolder, true);
}
//Sleep for 5 second
System.Threading.Thread.Sleep(new TimeSpan(0, 0, 5));
//Check whether Parent Folder Exist
if (Directory.Exists(ParentFolder))
{
//Get Parent File information to check whether it contains any file or folder
ZlpDirectoryInfo DeleteParentFolder = new ZlpDirectoryInfo(ParentFolder);
if (DeleteParentFolder.GetFiles().Length == 0 && DeleteParentFolder.GetDirectories().Length == 0)
{
//Delete Parent Folder
Directory.Delete(ParentFolder, true);
}
}
}
catch (IOException)
{
if (ZlpIOHelper.DirectoryExists(ChildFolder))
Directory.Delete(ChildFolder);
if (ZlpIOHelper.DirectoryExists(ParentFolder))
Directory.Delete(ParentFolder);
}
catch (UnauthorizedAccessException)
{
if (ZlpIOHelper.DirectoryExists(ChildFolder))
Directory.Delete(ChildFolder);
if (ZlpIOHelper.DirectoryExists(ParentFolder))
Directory.Delete(ParentFolder);
}
the delete code gives error 'Directory is not empty.' but the files gets deleted from the location 'D:\Active Folder\ReadyTobeTransfer\ABC\XYZ' however it doesn't delete the parent and child folder.
this is the error message
The directory is not empty. StackTrace:- at
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at
System.IO.Directory.DeleteHelper(String fullPath, String userPath,
Boolean recursive, Boolean throwOnTopLevelDirectoryNotFound) at
System.IO.Directory.Delete(String fullPath, String userPath, Boolean
recursive, Boolean checkHost)

Categories

Resources