I need to update a file which is on a remote server, using Silverlight and C#.
I created the file on the current machine and after that I tried to upload it using this example. It returned no error, but it doesn't upload my file either.
Could you help me?
this is the ashx code
<%# WebHandler Language="C#" Class="receiver" %>
using System;
using System.Web;
using System.IO;
public class receiver : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string filename = context.Request.QueryString["DB.xml"].ToString();
using (FileStream fs = File.Create(context.Server.MapPath("~/CLientBin" + filename)))
{
SaveFile(context.Request.InputStream, fs);
}
}
private void SaveFile(Stream stream, FileStream fs)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
public bool IsReusable {
get {
return false;
}
}
}
and this is the c# code:
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = "All files (*.*)|*.*|PNG Images (*.png)|*.png";
bool? retval = dlg.ShowDialog();
if (retval != null && retval == true)
{
try
{
UploadFile(dlg.File.Name, dlg.File.OpenRead());
titlu.Text = dlg.File.Name;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
titlu.Text = "No file selected...";
}
}
private void UploadFile(string fileName, Stream data)
{
UriBuilder ub = new UriBuilder("http://ganduri.elementfx.com/Handler.ashx");
ub.Query = string.Format("filename={0}", fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
c.OpenWriteAsync(ub.Uri);
}
private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
MessageBox.Show("Writed");
}
I have also checked the permissions to the ClientBin folder and are read/write permissions
When I run this code it shows me the "Writed" messageBox, but if I look in the server, the file isn't anywhere.
I have set a breakpoint in af ashx file functions and id doesn't reach any of them.
Think you need check upload folder for existence, and write access rights
Related
I have an active audio recording happening in WAV format with NAudio Library.
private void RecordStart() {
try {
_sourceStream = new WaveIn {
DeviceNumber = _recordingInstance.InputDeviceIndex,
WaveFormat =
new WaveFormat(
44100,
WaveIn.GetCapabilities(_recordingInstance.InputDeviceIndex).Channels)
};
_sourceStream.DataAvailable += SourceStreamDataAvailable;
if (!Directory.Exists(_recordingInstance.AudioFilePath)) {
Directory.CreateDirectory(_recordingInstance.AudioFilePath);
}
WaveFileWriter _waveWriter = new WaveFileWriter(
_recordingInstance.AudioFilePath + _recordingInstance.AudioFileName,
_sourceStream.WaveFormat);
_sourceStream.StartRecording();
}
catch (Exception exception) {
Log.Error("Recording failes", exception);
}
}
private void SourceStreamDataAvailable(object sender, WaveInEventArgs e) {
if (_waveWriter == null) return;
_waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
_waveWriter.Flush();
}
I want to copy the latest available content to another location. The copied file should be in WAV format, and should be able to play the available duration. Update the destination file, whenever more content is available.
I have Tried the following sample code (using NAudio) with a static WAV file, but the solution is not working.
The resulting WAV file created is corrupted - not in the correct format.
using (WaveFileReader reader = new WaveFileReader(remoteWavFile))
{
byte[] buffer = new byte[reader.Length];
int read = reader.Read(buffer, 0, buffer.Length);
}
When the recording is in progress, the code throws an exception "File is in use by another application".
I have solved the problem with help of NAudio Library itself.
When we only use the WaveFileReader class of NAudio. It will throw the exception - "file is in use by another application".
So I had to create a file stream, which opens the source file - live recording file, with File.Open(inPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) then pass this stream as an input of WaveFileReader.
Then create a WaveFileWritter class of NAudio, with the same WavFormat of the reader.
copied below is the code, i have used.
public static void CopyWavFile(string inPath, string outPath){
using (var fs = File.Open(inPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){
using (var reader = new WaveFileReader(fs)){
using (var writer = new WaveFileWriter(outPath, reader.WaveFormat)){
reader.Position = 0;
var endPos = (int)reader.Length;
var buffer = new byte[1024];
while (reader.Position < endPos){
var bytesRequired = (int)(endPos - reader.Position);
if (bytesRequired <= 0) continue;
var bytesToRead = Math.Min(bytesRequired, buffer.Length);
var bytesRead = reader.Read(buffer, 0, bytesToRead);
if (bytesRead > 0){
writer.Write(buffer, 0, bytesRead);
}
}
}
}
}
}
I'm trying to use the following snippet in order download files via the SaveFileDialog in Silverlight:
public void SaveMediaLocal(string fileName)
{
FileInfo fInfo = new FileInfo(fileName);
if (fInfo.Exists)
{
if (fInfo.Length > 0)
{
string extension = fInfo.Extension;
SaveFileDialog dialog = new SaveFileDialog()
{
DefaultExt = extension,
Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, fInfo.Extension),
FilterIndex = 1,
DefaultFileName = fInfo.Name
};
if (dialog.ShowDialog() == true)
{
try
{
bool cancelFlag = false;
byte[] buffer = new byte[1024 * 1024]; // 1GB buffer
using (FileStream dest = (FileStream)dialog.OpenFile())
{
using (FileStream source = new FileStream(fInfo.FullName, FileMode.Open, FileAccess.Read))
{
long fileLength = source.Length;
long totalBytes = 0;
int currentBlockSize = 0;
while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytes += currentBlockSize;
double percentage = (double)totalBytes * 100.0 / fileLength;
dest.Write(buffer, 0, currentBlockSize);
}
}
}
}
catch
{
}
}
}
else
{
//no results
}
}
}
When I use this snippet; Silverlight freezes until the download completes.
When I use this snippet instead, the UI is responsive, but doesn't work on bigger files.
using (Stream stream = dialog.OpenFile())
{
Byte[] bytes = File.ReadAllBytes(fileName);
stream.Write(bytes, 0, bytes.Length);
}
Is there something that I'm missing here?
Don't do the operation on the GUI thread. That is why it gets unresponsive. Either create a new thread or async process and do the operation in the background.
I want to compress a Excel file to .zip or .cap extension. The code Used to do that it is compressing the file but that zip file can't be unzip. while unzip that i am getting the error file file corrupted or can't be unzip.
The code I am using:
static public bool CompressFile(string file, string outputFile)
{
try
{
using (var inFile = File.OpenRead(file))
{
using (var outFile = File.Create(outputFile))
{
using (var compress = new GZipStream(outFile, CompressionMode.Compress, false))
{
byte[] buffer = new byte[inFile.Length];
int read = inFile.Read(buffer, 0, buffer.Length);
while (read > 0)
{
compress.Write(buffer, 0, read);
read = inFile.Read(buffer, 0, buffer.Length);
}
}
}
}
return true;
}
catch (IOException ex)
{
MessageBox.Show(string.Format("Error compressing file: {0}", ex.Message));
return false;
}
}
Even i go some link to get the proper solution. But nothing is workout.I need some suggestion to get the proper solution. Any answer please.
This code uses the SharpZipLib library and will compress files that can be uncompressed no problems
private void Zip()
{
string output = #"C:\TEMP\test.zip";
string input = #"C:\TEMP\test.xlsx";
using (var zipStream = new ZipOutputStream(System.IO.File.Create(output)))
{
zipStream.SetLevel(9);
var buffer = new byte[4096];
var entry = new ZipEntry(Path.GetFileName(input));
zipStream.PutNextEntry(entry);
using (FileStream fs = System.IO.File.OpenRead(input))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
zipStream.Finish();
zipStream.Close();
}
}
I want to show image with extension *.ico and I use Stream to do it. But I have a problem that.
With Extension *.jpg, *.bmp... Image show ok but *.ico, it does not show
Here is my code:
private void OutputStream(string fileName)
{
try
{
Stream dataStream = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPFile spFile = web.GetFile(fileName);
dataStream = spFile.OpenBinaryStream();
this.HandleOutputStream(dataStream);
});
}
catch (System.Threading.ThreadAbortException exTemp)
{
logger.Error("KBStreamPicture::OutputStream", exTemp);
}
catch (Exception ex)
{
//System.Diagnostics.Debug.Write("OutputStream::" + ex);
logger.Error("KBStreamPicture::OutputStream", ex);
}
}
and
private void HandleOutputStream(Stream dataStream)
{
const int bufferSize = 16384; //16KB
using (Stream file = dataStream)
{
if (file != null)
{
this.Page.Response.Clear();
this.Page.Response.Cache.SetCacheability(System.Web.HttpCacheability.Private);
this.Page.Response.Cache.SetExpires(DateTime.Now.AddMinutes(20)); //only cache 20 minutes
byte[] buffer = new byte[bufferSize];
int count = file.Read(buffer, 0, bufferSize);
while (count > 0)
{
if (this.Page.Response.IsClientConnected)
{
this.Page.Response.OutputStream.Write(buffer, 0, count);
count = file.Read(buffer, 0, bufferSize);
}
else
{
count = -1;
}
}
this.Page.Response.End();
}
}
}
Please help me to resolve that problem.
You're not setting the ContentType property on the Response. Try setting the ContentType to image/x-icon (please note that the "correct" content type may be image/vnd.microsoft.icon, but this post seems to indicate you may run into problems with that type).
The code should look something like:
this.Page.Response.Clear();
this.Page.Response.Cache.SetCacheability(System.Web.HttpCacheability.Private);
this.Page.Response.Cache.SetExpires(DateTime.Now.AddMinutes(20));
this.Page.Response.ContentType = "image/x-icon";
As part of an upcoming project at my university, I need to write a client that downloads a media file from a server and writes it to the local disk. Since these files can be very large, I need to implement partial download and serialization in order to avoid excessive memory use.
What I came up with:
namespace PartialDownloadTester
{
using System;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net;
using System.Text;
public class DownloadClient
{
public static void Main(string[] args)
{
var dlc = new DownloadClient(args[0], args[1], args[2]);
dlc.DownloadAndSaveToDisk();
Console.ReadLine();
}
private WebRequest request;
// directory of file
private string dir;
// full file identifier
private string filePath;
public DownloadClient(string uri, string fileName, string fileType)
{
this.request = WebRequest.Create(uri);
this.request.Method = "GET";
var sb = new StringBuilder();
sb.Append("C:\\testdata\\DownloadedData\\");
this.dir = sb.ToString();
sb.Append(fileName + "." + fileType);
this.filePath = sb.ToString();
}
public void DownloadAndSaveToDisk()
{
// make sure directory exists
this.CreateDir();
var response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Content length: " + response.ContentLength);
var rStream = response.GetResponseStream();
int bytesRead = -1;
do
{
var buf = new byte[2048];
bytesRead = rStream.Read(buf, 0, buf.Length);
rStream.Flush();
this.SerializeFileChunk(buf);
}
while (bytesRead != 0);
}
private void CreateDir()
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
private void SerializeFileChunk(byte[] bytes)
{
Contract.Requires(!Object.ReferenceEquals(bytes, null));
FileStream fs = File.Open(filePath, FileMode.Append);
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
}
}
}
For testing purposes, I've used the following parameters:
"http://itu.dk/people/janv/mufc_abc.jpg" "mufc_abc" "jpg"
However, the picture is incomplete (only the first ~10% look right) even though the content length prints 63780 which is the actual size of the image.
So my questions are:
Is this the right way to go for partial download and serialization or is there a better/easier approach?
Is the full content of the response stream stored in client memory? If this is the case, do I need to use HttpWebRequest.AddRange to partially download data from the server in order to conserve my client's memory?
How come the serialization fails and I get a broken image?
Do I introduce a lot of overhead when I use the FileMode.Append? (msdn states that this option "seeks to the end of the file")
Thanks in advance
You could definitely simplify your code using a WebClient:
class Program
{
static void Main()
{
DownloadClient("http://itu.dk/people/janv/mufc_abc.jpg", "mufc_abc.jpg");
}
public static void DownloadClient(string uri, string fileName)
{
using (var client = new WebClient())
{
using (var stream = client.OpenRead(uri))
{
// work with chunks of 2KB => adjust if necessary
const int chunkSize = 2048;
var buffer = new byte[chunkSize];
using (var output = File.OpenWrite(fileName))
{
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
}
}
}
Notice how I am writing only the number of bytes I have actually read from the socket to the output file and not the entire 2KB buffer.
I don't know if this is the source of the problem, however I would change the loop like this
const int ChunkSize = 2048;
var buf = new byte[ChunkSize];
var rStream = response.GetResponseStream();
do {
int bytesRead = rStream.Read(buf, 0, ChunkSize);
if (bytesRead > 0) {
this.SerializeFileChunk(buf, bytesRead);
}
} while (bytesRead == ChunkSize);
The serialize method would get an additional argument
private void SerializeFileChunk(byte[] bytes, int numBytes)
and then write the right number of bytes
fs.Write(bytes, 0, numBytes);
UPDATE:
I do not see the need for closing and reopening the file each time. I also would use the using statement, which closes the resources, even if an exception should occur. The using statement calls the Dispose() method of the resource at the end, which in turn calls Close() in the case of file streams. using can be applied to all types implementing IDisposable.
var buf = new byte[2048];
using (var rStream = response.GetResponseStream()) {
using (FileStream fs = File.Open(filePath, FileMode.Append)) {
do {
bytesRead = rStream.Read(buf, 0, buf.Length);
fs.Write(bytes, 0, bytesRead);
} while (...);
}
}
The using statement does something like this
{
var rStream = response.GetResponseStream();
try
{
// do some work with rStream here.
} finally {
if (rStream != null) {
rStream.Dispose();
}
}
}
Here is the solution from Microsoft: http://support.microsoft.com/kb/812406
Updated 2021-03-16: seems the original article is not available now. Here is the archived one: https://mskb.pkisolutions.com/kb/812406