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())
{
...
}
Related
I've got a windows service that I have to modify. Current code is this:
public IRecord2 GetRecord(string name)
{
string path = Path.Combine(this.DirectoryPath, name);
if (!File.Exists(path))
return null;
byte[] contents;
lock (locker) {
using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize:4096, useAsync:true)) //WHERE THE PROBLEM IS OCCURRING
{
using (BinaryReader br = new BinaryReader(fs))
{
contents = br.ReadBytes((int)fs.Length);
br.Close(); //unnecessary but threw it in just to be sure
fs.Close(); //unnecessary but threw it in just to be sure
}
}
}
return new Record2()
{
Name = name,
Contents = contents
};
}
Code that calls the function:
public void Process(string pickupFileName)
{
string uniqueId = DateTime.Now.ToString("(yyyy-MM-dd_HH-mm-ss)");
string exportFileName = Path.GetFileNameWithoutExtension(pickupFileName) + "_" + uniqueId + ".csv";
string archiveFileName = Path.GetFileNameWithoutExtension(pickupFileName) + "_" + uniqueId + Path.GetExtension(pickupFileName);
string unprocessedFileName = Path.GetFileNameWithoutExtension(pickupFileName) + "_" + uniqueId + Path.GetExtension(pickupFileName);
try
{
_logger.LogInfo(String.Format("Processing lockbox file '{0}'", pickupFileName));
IRecord2 record = _pickup.GetRecord(pickupFileName);
if (record == null)
return;
_archive.AddOrUpdate(new Record2() { Name = archiveFileName, Contents = record.Contents });
string pickupFileContents = UTF8Encoding.UTF8.GetString(record.Contents);
IBai2Document document = Bai2Document.CreateFromString(pickupFileContents);
StringBuilder sb = Export(document);
_export.AddOrUpdate(new Record2() { Name = exportFileName, Contents = Encoding.ASCII.GetBytes(sb.ToString()) });
_pickup.Delete(pickupFileName);
}
catch(Exception ex)
{
throw ex;
}
}
Function that calls Process:
public void Process()
{
foreach (ConfigFolderPath configFolderPath in _configSettings.ConfigFolderPaths)
{
IRecordRepository pickup = new FileRepository(configFolderPath.PickupFolderPath);
IRecordRepository export = new FileRepository(configFolderPath.ExportFolderPath);
IRecordRepository archive = new FileRepository(configFolderPath.ArchiveFolderPath);
IRecordRepository unprocessed = new FileRepository(configFolderPath.UnprocessedFolderPath);
Converter converter = new Converter(Logger,pickup, export, archive, unprocessed);
foreach (string fileName in pickup.GetNames())
{
if (_configSettings.SupportedFileExtensions.Count > 0 && !_configSettings.SupportedFileExtensions.Any(extension => extension.ToLower() == Path.GetExtension(fileName).ToLower()))
continue;
Action action = () => converter.Process(fileName);
_queue.TryEnqueue(action, new WorkTicket() { Description = String.Format("Processing '{0}'", fileName), SequentialExecutionGroup = fileName });
}
}
}
When 1 file is sent to the service, it processes and reads the file correctly. However, if two files are sent (difference of 3 minutes), the first file will process correctly, but the second will give me "System.IO.IOException: The process cannot access the file "filename" because it is being used by another process.
Is the solution to use a mutex as per https://stackoverflow.com/a/29941548/4263285 or is there a better solution to solve this?
Edit: More context:
Service is constantly running - as soon as files are dropped into a folder, it begins the process.
get the file data (function up above)
take the data, transform it, and put it into a different file
Delete the original file from the one up above
rinse and repeat if more files
if one file is placed in the folder, it works correctly.
if two files are placed in the folder, it breaks on the second file
if service is stopped and restarted, it works again
In your code add ".Close()" here, at the end of the line :
using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize:4096, useAsync:true).Close())
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
Can anyone tell me how to get rid of the error
The process cannot access the file because it is being used by another process
Here is my code
if (!File.Exists(FlagFilePath))
{
Debug.WriteLine("Trying to download sales data file ");
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = ConfigurationManager.AppSettings["SFTPDomain"],
UserName = ConfigurationManager.AppSettings["SFTPUser"],
Password = ConfigurationManager.AppSettings["SFTPPass"],
PortNumber = Convert.ToInt32(ConfigurationManager.AppSettings["SFTPPortNumber"]),
GiveUpSecurityAndAcceptAnySshHostKey = true,
};
using (Session session = new Session())
{
//Attempts to connect to your SFtp site
session.Open(sessionOptions);
//Get SFtp File
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary; //The Transfer Mode - Automatic, Binary, or Ascii
transferOptions.FilePermissions = null; //Permissions applied to remote files;
transferOptions.PreserveTimestamp = false; //Set last write time of destination file
//to that of source file - basically change the timestamp to match destination and source files.
transferOptions.ResumeSupport.State = TransferResumeSupportState.Off;
//SFTP File Path
Sftp_RemotePath = ConfigurationManager.AppSettings["SFTPFileName"].ToString();
//Delete File if Exist
if (System.IO.File.Exists(FilePath))
{
System.IO.File.Delete(FilePath);
}
//the parameter list is: remote Path, Local Path with filename
TransferOperationResult transferOperationResult = session.GetFiles(Sftp_RemotePath, FilePath , false, transferOptions);
//Throw on any error
transferOperationResult.Check();
Debug.WriteLine("Downloaded fresh sales data file!");
}
}
I am using MVC and have two controllers which access this class. When I run the controllers one at a time then it works fine but when I run both controllers together then I get this error in one of the controller:
WinSCP.SessionRemoteException: Can't create file 'D:\TESTING\SFTP\Data.csv'. ---> WinSCP.SessionRemoteException: System Error.
Code: 32.
The process cannot access the file because it is being used by another process
--- End of inner exception stack trace ---
at WinSCP.OperationResultBase.Check()
at JetStarAPI.Models.SFTPClient.DownloadFile(String FilePath) in D:\TESTING\SFTP\Models\SFTPClient.cs:line 65}
I am getting this error after this line
transferOperationResult.Check();
If I change the name of the file here
TransferOperationResult transferOperationResult = session.GetFiles(Sftp_RemotePath, FilePath+Path.GetRandomFileName() , false, transferOptions);
It works fine and save the file with random file name but I want to pass my FileName. How to solve this?
static bool IsDownloadInProgress = false;
public static string DownloadFile(string FilePath)
{
string SalesStatus = "ok";
try
{
if (!File.Exists(FlagFilePath) && !IsDownloadInProgress)
{
Debug.WriteLine("Trying to download sales data file ");
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = ConfigurationManager.AppSettings["SFTPDomain"],
UserName = ConfigurationManager.AppSettings["SFTPUser"],
Password = ConfigurationManager.AppSettings["SFTPPass"],
PortNumber = Convert.ToInt32(ConfigurationManager.AppSettings["SFTPPortNumber"]),
GiveUpSecurityAndAcceptAnySshHostKey = true,
};
using (Session session = new Session())
{
//Attempts to connect to your SFtp site
session.Open(sessionOptions);
//Get SFtp File
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary; //The Transfer Mode - Automatic, Binary, or Ascii
transferOptions.FilePermissions = null; //Permissions applied to remote files;
transferOptions.PreserveTimestamp = false; //Set last write time of destination file
//to that of source file - basically change the timestamp to match destination and source files.
transferOptions.ResumeSupport.State = TransferResumeSupportState.On;
//SFTP File Path
Sftp_RemotePath = ConfigurationManager.AppSettings["SFTPFileName"].ToString();
//Delete File if Exist
if (System.IO.File.Exists(FilePath))
{
System.IO.File.Delete(FilePath);
}
//Throw on any error
session.FileTransferred += OnFileTransferComplete;
IsDownloadInProgress = true;
//the parameter list is: remote Path, Local Path with filename
// string result = Path.GetRandomFileName();
session.GetFiles(Sftp_RemotePath,FilePath,false, transferOptions).Check();
session.Dispose();
// File.Move(FilePath, "foo2.png");
Debug.WriteLine("Downloaded fresh sales data file!");
}
}
}
catch (Exception ex)
{
string _errorMsg = "";
// Setting Sales Status values
if (ex.InnerException != null)
{
if (ex.InnerException.Message.Contains("Authentication failed"))
{
_errorMsg = ex.InnerException.Message;
Debug.WriteLine("wrong username/password");
SalesStatus = "2";
}
else if (ex.InnerException.Message.Contains("No such file or directory"))
{
_errorMsg = ex.InnerException.Message;
Debug.WriteLine("File is not Available");
SalesStatus = "3";
}
}
else
{
_errorMsg = ex.Message;
Debug.WriteLine("General SFTP Error");
SalesStatus = "4";
}
//Create log error file
if (!File.Exists(FlagFilePath))
{
// create SFTP LocalErrorFlag
Debug.WriteLine("Creating SFTP flag file");
System.IO.File.WriteAllText(FlagFilePath, "SFTP Error: " + _errorMsg);
}
else
{
Debug.WriteLine("SFTP error Flag file already exists");
}
}
return SalesStatus;
}
private static void OnFileTransferComplete(object sender, TransferEventArgs e)
{
IsDownloadInProgress = false;
((Session)sender).FileTransferred -= OnFileTransferComplete;
}
I'm looking for a way for me to get the folder name which is located on (for example) http://example.com/download/"foldername here"
The reason for this is because I have a c# program which always downloads a .zip if you don't allready have it, but currently it won't download a new version.
Example: Currently it downloads from http://example.com/download/1.0/file.zip, if you allready have the folder it checks for, it won't download it, but if you do have that folder, it won't download from http://example.com/download/2.0/file.zip, which contains the new version. I have made a file which contains the current version, but how can I get my program to check that file against the folder in which the newest version resides?
Edit: I reworked my code so it downloads a version.txt file first and reads it contents, which contains the latest version of the download.
Code:
if (radUseFile.Checked)
{
//get latest version on website
WebClient modver = new WebClient();
modver.UseDefaultCredentials = true;
modver.DownloadFile("http://www.example.com/download/version.txt", tempdir _
+ "version.txt");
using (StreamReader ver = new StreamReader(tempdir + "version.txt"))
{
siteversion = ver.ReadToEnd();
}
File.Delete(tempdir + "version.txt");
if (Directory.Exists(folder))
{
if (File.Exists(folder + "\\version.txt"))
{
using (StreamReader sr = new StreamReader(folder + "\\version.txt"))
{
latestversion = sr.ReadToEnd();
}
if (latestversion != siteversion)
{
uptodate = false;
}
else
{
uptodate = true;
}
}
}
else
{
uptodate = false;
}
if (!uptodate)
{
//download and extract the files
WebClient downloader = new WebClient();
label4.Text = "Downloading full client. May take a while";
this.Update();
downloader.UseDefaultCredentials = true;
downloader.DownloadFile("http://www.example.com/download" + siteversion _
+ "/zipfile.zip", templocation + "zipfile.zip");
label4.Text = "Extracting...";
Shell32.Shell sc = new Shell32.Shell();
Directory.CreateDirectory(tempdir);
Shell32.Folder output = sc.NameSpace(tempdir);
Shell32.Folder input = sc.NameSpace(tempdir + "zipfile.zip");
output.CopyHere(input.Items(), 4);
label4.Text = "Cleaning up...";
File.Delete(tempdir + "zipfile.zip");
new Microsoft.VisualBasic.Devices.Computer().FileSystem.CopyDirectory(tempdir,_
folderlocation, true);
Directory.Delete(tempdir, true);
uptodate = true;
}
}
else
{
uptodate = true;
}
This works for now, but I'm pretty sure this code can be improved, or the entire method as to how it takes the latest version
You could have a text file, containing the latest version number and where to download it from, in a permanent location, say http://example.com/download/latestversion.txt. Then use WebClient.DownloadString to retrieve that file, and take the appropriate action depending on the content of the file.
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
}
}
}