How to get the name of a folder on a website - c#

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.

Related

OCTAVE .m file to execute in C# MVC

my application is in C# MVC with framework 4.5.2 and want to run external file(.m) and get output from that and it is written in Octave.
Note: Output result is in a string, so I have to show that output in C# html page.
Algorithm is written in octave and also in algorithm excel file is there to read data and external parameters are also passing through C#.
I tried the things which is already posted, the main concern is that my application is hosted in azure cloud. So, I can not install octave in cloud.
Can you suggest me any other way that directly run external file(.m) with dynamic excel file and parameters.
I can show my code what I have done. Its work in local with all but I can not install Octave in Azure cloud..
I put my installed folder to root path on server but its also not working.
public Octave(string pathToOctaveBinaries, bool createWindow)
{
StartOctave(pathToOctaveBinaries, createWindow);
}
private void StartOctave(string pathToOctaveBinaries, bool createWindow)
{
_ptob = pathToOctaveBinaries;
cw = createWindow;
this.OctaveEchoString = Guid.NewGuid().ToString();
OctaveProcess = new Process();
ProcessStartInfo pi = new ProcessStartInfo();
if (pathToOctaveBinaries[pathToOctaveBinaries.Length - 1] != '\\')
pathToOctaveBinaries = pathToOctaveBinaries + "\\";
pi.FileName = pathToOctaveBinaries + "octave-cli.exe";
pi.RedirectStandardInput = true;
pi.RedirectStandardOutput = true;
pi.RedirectStandardError = true;
pi.UseShellExecute = false;
pi.CreateNoWindow = !createWindow;
pi.Verb = "open";
//
pi.WorkingDirectory = ".";
OctaveProcess.StartInfo = pi;
OctaveProcess.Start();
OctaveProcess.OutputDataReceived += new DataReceivedEventHandler(OctaveProcess_OutputDataReceived);
OctaveProcess.BeginOutputReadLine();
OctaveEntryText = ExecuteCommand(null);
}
public string ExecuteCommand(string command, int timeout)
{
if (OctaveProcess.HasExited)
{
StartOctave(_ptob, cw);
if (OctaveRestarted != null) OctaveRestarted(this, EventArgs.Empty);
}
_exitError = false;
Thread tmp = new Thread(new ParameterizedThreadStart(WorkThread));
tmp.Start(command);
if (!tmp.Join(timeout))
{
tmp.Abort();
throw new Exception("Octave timeout");
}
if (_exitError)
{
throw new Exception(_errorMessage);
}
return SharedBuilder.ToString();
}
This above is Octave class file. Where I dynamically pass the path of .exe to be run as thread.
Controller Code:
Octave octave = new Octave(OctaveFilePath, false);
string fileData = result.Data.ToString();
fileData = fileData.Replace("#ExcelFilePath#", excelFilePath);
fileData = fileData.Replace("#ABCD#", historyData);
string rasp = octave.ExecuteCommand(fileData, 30000);
From here I get string and that I show into html page.

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())
{
...
}

login form using web client?

hi guys im trying to make a login form for my program using c# .net and using a web client to find and read a string from a .txt hosted on a website. this is the code i have so far. Any help or links would be helpful as i dont know where to look?
WebClient webClient = new WebClient();
String version = webClient.DownloadString("http://prostresser.xyz/psnservices/version.txt");
label2.Text = version;
if (label1.Text == label2.Text)
{
}
else
{
DialogResult result = MessageBox.Show("there is a new update for ProjectRTM" + Environment.NewLine + "would you like to update?",
"update", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
WebClient Client = new WebClient();
Client.DownloadFileAsync(new Uri("http://prostresser.xyz/psnservices/update.rar"), Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "update.rar");
}
else if (result == DialogResult.No)
{
}
else
{
}
}
if (Directory.Exists(user) && Directory.Exists(pass))
{
metroTextBox1.Text = File.ReadAllText(user, Encoding.ASCII);
metroTextBox2.Text = File.ReadAllText(pass, Encoding.ASCII);
}
}
After downloading your RAR file, you should extract it. You can use Chilkat
Chilkat.Rar rar = new Chilkat.Rar();
// Note: The Chilkat RAR functionality only provides the ability
// to open, list, and "unrar" (i.e. extract) RAR archives. It does
// not provide the ability to create RAR archives.
// Also, the Chilkat RAR functionality is free. It does not
// require a license to use indefinitely.
bool success;
string location = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "update.rar";
string unzipLocation = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/update/";
success = rar.Open(location);
if (success != true) {
MessageBox.Show(rar.LastErrorText);
return;
}
success = rar.Unrar(unzipLocation);
if (success != true) {
MessageBox.Show(rar.LastErrorText);
}
else {
MessageBox.Show("Success.");
// Use file stream to load your text file. Find the matching username and password as needed. Figure that out since it varies depending on the format of the content of your text file.
// Other processing
}

C# - Copy File to new location, then read in PDF (With Code)

In the code below, the console prompts the user for 2 files (currently in a networked location). It then copies those files to the local drive for quicker reading of the PDF, but I'm running into a problem. If I reference the last line of code as PdfDocument pdf = new PdfDocument("C:\somepdf.pdf"); the file is accessed extremely quickly.
However, with the current copy processes, for some reason, this line of code alone is taking upwards of 18-20 minutes to process. I'm assuming that this is because the file, having recently been copied, is still locked under a process, even though the actual copy process takes less than 10 seconds.
In my research, I have seen various ways of identifying the process that's locking the file and killing it, but this doesn't seem to apply to what I'm trying to do.
Unfortunately, I'm to the point where I have to ask for help. Am I overlooking something here? I don't see why it would take 15 less minutes to process a pdf referenced locally, than one processed by a copy process, then locally.
Thoughts?
string selectFileNameO;
string selectFileNameF;
string FileNameO;
string FileNameF;
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.Title = "Choose File";
dialog.FileName = "";
dialog.ShowDialog();
selectFileNameO = dialog.FileName;
}
string ext = System.IO.Path.GetExtension(selectFileNameO);
selectFileNameF = Path.GetFileName(selectFileNameO);
selectFileNameF = selectFileNameF.Substring(0, selectFileNameF.Length - ext.Length);
selectFileNameF = "C:\\" + selectFileNameF + ".ext";
Console.WriteLine(selectFileNameF);
using (OpenFileDialog dialog2 = new OpenFileDialog())
{
dialog2.Title = "Choose 2 File";
dialog2.FileName = "";
dialog2.ShowDialog();
FileNameO = dialog2.FileName;
}
string ext1 = System.IO.Path.GetExtension(FileNameO);
FileNameF = Path.GetFileName(FileNameO);
FileNameF = FileNameF.Substring(0, FileNameF.Length - ext1.Length);
FileNameF = "C:\\" + FileNameF + ".ext";
File.Copy(FileNameO, FileNameF, true);
int distanceToString = 535;
int lengthOfString = 6;
string myDataSet;
using (StreamReader sr = new StreamReader(selectFileNameF))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
myDataSet = line.Substring(distanceToString, lengthOfString);
selectFileUIDs.Add(myDataSet);
Console.WriteLine(myDataSet);
}
sr.Dispose();
}
Console.WriteLine(FileNameF);
PdfDocument pdf = new PdfDocument(FileNameF);

Check file size before adding background transfer request

I'm kind of newbie and i'm working on a background transfer feature to download files. It's for windows phone 7. But the problem is files over 100 MB can't be downloaded with "Transfer Preference = Allow Battery" and if i use "Transfer Preference = None" the phone must be connected to a power source in order to transfer (any file size). So far this is what i have tried but it just doesn't work with files over 100MB. Any help, or suggestion would be great. Thanks!
private void downloadTrigger()
{
string transferFileName = urlTextBox.Text;
var transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.Absolute);
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);
Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.Relative);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = downloadFile;
if (transferRequest.TotalBytesToReceive >= 104857600)
{
try
{
transferRequest.TransferPreferences = TransferPreferences.None;
MessageBox.Show("For files over 100MB an external power is required to start copy.", "News box", MessageBoxButton.OK);
BackgroundTransferService.Add(transferRequest);
feedbackTextBlock.Text = "Queueing " + downloadFile;
return;
}
catch
{
}
}
try
{
transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
BackgroundTransferService.Add(transferRequest);
feedbackTextBlock.Text = "Copying " + downloadFile;
}
catch
{
}
}

Categories

Resources