Search Results

Search found 451 results on 19 pages for 'filestream'.

Page 3/19 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Programmatically downloaded file is larger than it should be

    - by Dan Revell
    I'm trying to download a file from SharePoint. The file itself is an InfoPath template although this is probably inconsequential. If I put the url into internet explorer and save the file to disk, it comes in at 4.47KB and works correctly. If I try to download from the same Url in code the it comes back as 21.9KB and is corrupt. Why it's coming down as corrupt I'm trying to work out. The following are two ways of downloading the file that both produce the corrupt file at 21.9KB: /// web client { WebClient wc = new WebClient(); wc.Credentials = CredentialCache.DefaultCredentials; wc.DownloadFile(templateUri, file); byte[] bytes = wc.DownloadData(templateUri); } /// web request { WebRequest request = WebRequest.Create(templateUri); request.Credentials = CredentialCache.DefaultCredentials; WebResponse responce = request.GetResponse(); StreamReader sr = new StreamReader(responce.GetResponseStream()); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sr.ReadToEnd()); } And this is how I write the data to disk using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write)) { fs.Write(bytes, 0, bytes.Length); }

    Read the article

  • How to get file path using FileUpload to be read by FileStream?

    - by john ryan
    I have a Method that open excel file and read it through exceldatareaderClass that i have downloaded in codeplex by using filestream. Currently I just declared the exact directory where the filestream open an excel file.And it works fine. Stream stream = new FileStream("C:\\" + FileUpload.PostedFile.FileName, FileMode.Open, FileAccess.Read, FileShare.Read); Now i need to read the excel file wherever location the user place it like on windows forms fileupload.FileStream needs the exact location where the file is located. How to do this.? Example: Sample.xls is located on My Documents the file path should be like : C:\Documents and Settings\user\My Documents\ string openpath ="" ;//filepath Stream stream = new FileStream(openpath+ FileUpload.PostedFile.FileName, FileMode.Open, FileAccess.Read, FileShare.Read); Thanks in Regards

    Read the article

  • Implementing an async "read all currently available data from stream" operation

    - by Jon
    I recently provided an answer to this question: C# - Realtime console output redirection. As often happens, explaining stuff (here "stuff" was how I tackled a similar problem) leads you to greater understanding and/or, as is the case here, "oops" moments. I realized that my solution, as implemented, has a bug. The bug has little practical importance, but it has an extremely large importance to me as a developer: I can't rest easy knowing that my code has the potential to blow up. Squashing the bug is the purpose of this question. I apologize for the long intro, so let's get dirty. I wanted to build a class that allows me to receive input from a console's standard output Stream. Console output streams are of type FileStream; the implementation can cast to that, if needed. There is also an associated StreamReader already present to leverage. There is only one thing I need to implement in this class to achieve my desired functionality: an async "read all the data available this moment" operation. Reading to the end of the stream is not viable because the stream will not end unless the process closes the console output handle, and it will not do that because it is interactive and expecting input before continuing. I will be using that hypothetical async operation to implement event-based notification, which will be more convenient for my callers. The public interface of the class is this: public class ConsoleAutomator { public event EventHandler<ConsoleOutputReadEventArgs> StandardOutputRead; public void StartSendingEvents(); public void StopSendingEvents(); } StartSendingEvents and StopSendingEvents do what they advertise; for the purposes of this discussion, we can assume that events are always being sent without loss of generality. The class uses these two fields internally: protected readonly StringBuilder inputAccumulator = new StringBuilder(); protected readonly byte[] buffer = new byte[256]; The functionality of the class is implemented in the methods below. To get the ball rolling: public void StartSendingEvents(); { this.stopAutomation = false; this.BeginReadAsync(); } To read data out of the Stream without blocking, and also without requiring a carriage return char, BeginRead is called: protected void BeginReadAsync() { if (!this.stopAutomation) { this.StandardOutput.BaseStream.BeginRead( this.buffer, 0, this.buffer.Length, this.ReadHappened, null); } } The challenging part: BeginRead requires using a buffer. This means that when reading from the stream, it is possible that the bytes available to read ("incoming chunk") are larger than the buffer. Remember that the goal here is to read all of the chunk and call event subscribers exactly once for each chunk. To this end, if the buffer is full after EndRead, we don't send its contents to subscribers immediately but instead append them to a StringBuilder. The contents of the StringBuilder are only sent back whenever there is no more to read from the stream. private void ReadHappened(IAsyncResult asyncResult) { var bytesRead = this.StandardOutput.BaseStream.EndRead(asyncResult); if (bytesRead == 0) { this.OnAutomationStopped(); return; } var input = this.StandardOutput.CurrentEncoding.GetString( this.buffer, 0, bytesRead); this.inputAccumulator.Append(input); if (bytesRead < this.buffer.Length) { this.OnInputRead(); // only send back if we 're sure we got it all } this.BeginReadAsync(); // continue "looping" with BeginRead } After any read which is not enough to fill the buffer (in which case we know that there was no more data to be read during the last read operation), all accumulated data is sent to the subscribers: private void OnInputRead() { var handler = this.StandardOutputRead; if (handler == null) { return; } handler(this, new ConsoleOutputReadEventArgs(this.inputAccumulator.ToString())); this.inputAccumulator.Clear(); } (I know that as long as there are no subscribers the data gets accumulated forever. This is a deliberate decision). The good This scheme works almost perfectly: Async functionality without spawning any threads Very convenient to the calling code (just subscribe to an event) Never more than one event for each time data is available to be read Is almost agnostic to the buffer size The bad That last almost is a very big one. Consider what happens when there is an incoming chunk with length exactly equal to the size of the buffer. The chunk will be read and buffered, but the event will not be triggered. This will be followed up by a BeginRead that expects to find more data belonging to the current chunk in order to send it back all in one piece, but... there will be no more data in the stream. In fact, as long as data is put into the stream in chunks with length exactly equal to the buffer size, the data will be buffered and the event will never be triggered. This scenario may be highly unlikely to occur in practice, especially since we can pick any number for the buffer size, but the problem is there. Solution? Unfortunately, after checking the available methods on FileStream and StreamReader, I can't find anything which lets me peek into the stream while also allowing async methods to be used on it. One "solution" would be to have a thread wait on a ManualResetEvent after the "buffer filled" condition is detected. If the event is not signaled (by the async callback) in a small amount of time, then more data from the stream will not be forthcoming and the data accumulated so far should be sent to subscribers. However, this introduces the need for another thread, requires thread synchronization, and is plain inelegant. Specifying a timeout for BeginRead would also suffice (call back into my code every now and then so I can check if there's data to be sent back; most of the time there will not be anything to do, so I expect the performance hit to be negligible). But it looks like timeouts are not supported in FileStream. Since I imagine that async calls with timeouts are an option in bare Win32, another approach might be to PInvoke the hell out of the problem. But this is also undesirable as it will introduce complexity and simply be a pain to code. Is there an elegant way to get around the problem? Thanks for being patient enough to read all of this. Update: I definitely did not communicate the scenario well in my initial writeup. I have since revised the writeup quite a bit, but to be extra sure: The question is about how to implement an async "read all the data available this moment" operation. My apologies to the people who took the time to read and answer without me making my intent clear enough.

    Read the article

  • Need help manipulating WAV (RIFF) Files at a byte level

    - by Eric
    I'm writing an an application in C# that will record audio files (*.wav) and automatically tag and name them. Wave files are RIFF files (like AVI) which can contain meta data chunks in addition to the waveform data chunks. So now I'm trying to figure out how to read and write the RIFF meta data to and from recorded wave files. I'm using NAudio for recording the files, and asked on their forums as well on SO for way to read and write RIFF tags. While I received a number of good answers, none of the solutions allowed for reading and writing RIFF chunks as easily as I would like. But more importantly I have very little experience dealing with files at a byte level, and think this could be a good opportunity to learn. So now I want to try writing my own class(es) that can read in a RIFF file and allow meta data to be read, and written from the file. I've used streams in C#, but always with the entire stream at once. So now I'm little lost that I have to consider a file byte by byte. Specifically how would I go about removing or inserting bytes to and from the middle of a file? I've tried reading a file through a FileStream into a byte array (byte[]) as shown in the code below. System.IO.FileStream waveFileStream = System.IO.File.OpenRead(@"C:\sound.wav"); byte[] waveBytes = new byte[waveFileStream.Length]; waveFileStream.Read(waveBytes, 0, waveBytes.Length); And I could see through the Visual Studio debugger that the first four byte are the RIFF header of the file. But arrays are a pain to deal with when performing actions that change their size like inserting or removing values. So I was thinking I could then to the byte[] into a List like this. List<byte> list = waveBytes.ToList<byte>(); Which would make any manipulation of the file byte by byte a whole lot easier, but I'm worried I might be missing something like a class in the System.IO name-space that would make all this even easier. Am I on the right track, or is there a better way to do this? I should also mention that I'm not hugely concerned with performance, and would prefer not to deal with pointers or unsafe code blocks like this guy. If it helps at all here is a good article on the RIFF/WAV file format.

    Read the article

  • Implementing a robust async stream reader

    - by Jon
    I recently provided an answer to this question: C# - Realtime console output redirection. As often happens, explaining stuff (here "stuff" was how I tackled a similar problem) leads you to greater understanding and/or, as is the case here, "oops" moments. I realized that my solution, as implemented, has a bug. The bug has little practical importance, but it has an extremely large importance to me as a developer: I can't rest easy knowing that my code has the potential to blow up. Squashing the bug is the purpose of this question. I apologize for the long intro, so let's get dirty. I wanted to build a class that allows me to receive input from a Stream in an event-based manner. The stream, in my scenario, is guaranteed to be a FileStream and there is also an associated StreamReader already present to leverage. The public interface of the class is this: public class MyStreamManager { public event EventHandler<ConsoleOutputReadEventArgs> StandardOutputRead; public void StartSendingEvents(); public void StopSendingEvents(); } Obviously this specific scenario has to do with a console's standard output, but that is a detail and does not play an important role. StartSendingEvents and StopSendingEvents do what they advertise; for the purposes of this discussion, we can assume that events are always being sent without loss of generality. The class uses these two fields internally: protected readonly StringBuilder inputAccumulator = new StringBuilder(); protected readonly byte[] buffer = new byte[256]; The functionality of the class is implemented in the methods below. To get the ball rolling: public void StartSendingEvents(); { this.stopAutomation = false; this.BeginReadAsync(); } To read data out of the Stream without blocking, and also without requiring a carriage return char, BeginRead is called: protected void BeginReadAsync() { if (!this.stopAutomation) { this.StandardOutput.BaseStream.BeginRead( this.buffer, 0, this.buffer.Length, this.ReadHappened, null); } } The challenging part: BeginRead requires using a buffer. This means that when reading from the stream, it is possible that the bytes available to read ("incoming chunk") are larger than the buffer. Since we are only handing off data from the stream to a consumer, and that consumer may well have inside knowledge about the size and/or format of these chunks, I want to call event subscribers exactly once for each chunk. Otherwise the abstraction breaks down and the subscribers have to buffer the incoming data and reconstruct the chunks themselves using said knowledge. This is much less convenient to the calling code, and detracts from the usefulness of my class. To this end, if the buffer is full after EndRead, we don't send its contents to subscribers immediately but instead append them to a StringBuilder. The contents of the StringBuilder are only sent back whenever there is no more to read from the stream (thus preserving the chunks). private void ReadHappened(IAsyncResult asyncResult) { var bytesRead = this.StandardOutput.BaseStream.EndRead(asyncResult); if (bytesRead == 0) { this.OnAutomationStopped(); return; } var input = this.StandardOutput.CurrentEncoding.GetString( this.buffer, 0, bytesRead); this.inputAccumulator.Append(input); if (bytesRead < this.buffer.Length) { this.OnInputRead(); // only send back if we 're sure we got it all } this.BeginReadAsync(); // continue "looping" with BeginRead } After any read which is not enough to fill the buffer, all accumulated data is sent to the subscribers: private void OnInputRead() { var handler = this.StandardOutputRead; if (handler == null) { return; } handler(this, new ConsoleOutputReadEventArgs(this.inputAccumulator.ToString())); this.inputAccumulator.Clear(); } (I know that as long as there are no subscribers the data gets accumulated forever. This is a deliberate decision). The good This scheme works almost perfectly: Async functionality without spawning any threads Very convenient to the calling code (just subscribe to an event) Maintains the "chunkiness" of the data; this allows the calling code to use inside knowledge of the data without doing any extra work Is almost agnostic to the buffer size (it will work correctly with any size buffer irrespective of the data being read) The bad That last almost is a very big one. Consider what happens when there is an incoming chunk with length exactly equal to the size of the buffer. The chunk will be read and buffered, but the event will not be triggered. This will be followed up by a BeginRead that expects to find more data belonging to the current chunk in order to send it back all in one piece, but... there will be no more data in the stream. In fact, as long as data is put into the stream in chunks with length exactly equal to the buffer size, the data will be buffered and the event will never be triggered. This scenario may be highly unlikely to occur in practice, especially since we can pick any number for the buffer size, but the problem is there. Solution? Unfortunately, after checking the available methods on FileStream and StreamReader, I can't find anything which lets me peek into the stream while also allowing async methods to be used on it. One "solution" would be to have a thread wait on a ManualResetEvent after the "buffer filled" condition is detected. If the event is not signaled (by the async callback) in a small amount of time, then more data from the stream will not be forthcoming and the data accumulated so far should be sent to subscribers. However, this introduces the need for another thread, requires thread synchronization, and is plain inelegant. Specifying a timeout for BeginRead would also suffice (call back into my code every now and then so I can check if there's data to be sent back; most of the time there will not be anything to do, so I expect the performance hit to be negligible). But it looks like timeouts are not supported in FileStream. Since I imagine that async calls with timeouts are an option in bare Win32, another approach might be to PInvoke the hell out of the problem. But this is also undesirable as it will introduce complexity and simply be a pain to code. Is there an elegant way to get around the problem? Thanks for being patient enough to read all of this.

    Read the article

  • Implementing a robust async stream reader for a console

    - by Jon
    I recently provided an answer to this question: C# - Realtime console output redirection. As often happens, explaining stuff (here "stuff" was how I tackled a similar problem) leads you to greater understanding and/or, as is the case here, "oops" moments. I realized that my solution, as implemented, has a bug. The bug has little practical importance, but it has an extremely large importance to me as a developer: I can't rest easy knowing that my code has the potential to blow up. Squashing the bug is the purpose of this question. I apologize for the long intro, so let's get dirty. I wanted to build a class that allows me to receive input from a Stream in an event-based manner. The stream, in my scenario, is guaranteed to be a FileStream and there is also an associated StreamReader already present to leverage. The public interface of the class is this: public class MyStreamManager { public event EventHandler<ConsoleOutputReadEventArgs> StandardOutputRead; public void StartSendingEvents(); public void StopSendingEvents(); } Obviously this specific scenario has to do with a console's standard output. StartSendingEvents and StopSendingEvents do what they advertise; for the purposes of this discussion, we can assume that events are always being sent without loss of generality. The class uses these two fields internally: protected readonly StringBuilder inputAccumulator = new StringBuilder(); protected readonly byte[] buffer = new byte[256]; The functionality of the class is implemented in the methods below. To get the ball rolling: public void StartSendingEvents(); { this.stopAutomation = false; this.BeginReadAsync(); } To read data out of the Stream without blocking, and also without requiring a carriage return char, BeginRead is called: protected void BeginReadAsync() { if (!this.stopAutomation) { this.StandardOutput.BaseStream.BeginRead( this.buffer, 0, this.buffer.Length, this.ReadHappened, null); } } The challenging part: BeginRead requires using a buffer. This means that when reading from the stream, it is possible that the bytes available to read ("incoming chunk") are larger than the buffer. Since we are only handing off data from the stream to a consumer, and that consumer may well have inside knowledge about the size and/or format of these chunks, I want to call event subscribers exactly once for each chunk. Otherwise the abstraction breaks down and the subscribers have to buffer the incoming data and reconstruct the chunks themselves using said knowledge. This is much less convenient to the calling code, and detracts from the usefulness of my class. Edit: There are comments below correctly stating that since the data is coming from a stream, there is absolutely nothing that the receiver can infer about the structure of the data unless it is fully prepared to parse it. What I am trying to do here is leverage the "flush the output" "structure" that the owner of the console imparts while writing on it. I am prepared to assume (better: allow my caller to have the option to assume) that the OS will pass me the data written between two flushes of the stream in exactly one piece. To this end, if the buffer is full after EndRead, we don't send its contents to subscribers immediately but instead append them to a StringBuilder. The contents of the StringBuilder are only sent back whenever there is no more to read from the stream (thus preserving the chunks). private void ReadHappened(IAsyncResult asyncResult) { var bytesRead = this.StandardOutput.BaseStream.EndRead(asyncResult); if (bytesRead == 0) { this.OnAutomationStopped(); return; } var input = this.StandardOutput.CurrentEncoding.GetString( this.buffer, 0, bytesRead); this.inputAccumulator.Append(input); if (bytesRead < this.buffer.Length) { this.OnInputRead(); // only send back if we 're sure we got it all } this.BeginReadAsync(); // continue "looping" with BeginRead } After any read which is not enough to fill the buffer, all accumulated data is sent to the subscribers: private void OnInputRead() { var handler = this.StandardOutputRead; if (handler == null) { return; } handler(this, new ConsoleOutputReadEventArgs(this.inputAccumulator.ToString())); this.inputAccumulator.Clear(); } (I know that as long as there are no subscribers the data gets accumulated forever. This is a deliberate decision). The good This scheme works almost perfectly: Async functionality without spawning any threads Very convenient to the calling code (just subscribe to an event) Maintains the "chunkiness" of the data; this allows the calling code to use inside knowledge of the data without doing any extra work Is almost agnostic to the buffer size (it will work correctly with any size buffer irrespective of the data being read) The bad That last almost is a very big one. Consider what happens when there is an incoming chunk with length exactly equal to the size of the buffer. The chunk will be read and buffered, but the event will not be triggered. This will be followed up by a BeginRead that expects to find more data belonging to the current chunk in order to send it back all in one piece, but... there will be no more data in the stream. In fact, as long as data is put into the stream in chunks with length exactly equal to the buffer size, the data will be buffered and the event will never be triggered. This scenario may be highly unlikely to occur in practice, especially since we can pick any number for the buffer size, but the problem is there. Solution? Unfortunately, after checking the available methods on FileStream and StreamReader, I can't find anything which lets me peek into the stream while also allowing async methods to be used on it. One "solution" would be to have a thread wait on a ManualResetEvent after the "buffer filled" condition is detected. If the event is not signaled (by the async callback) in a small amount of time, then more data from the stream will not be forthcoming and the data accumulated so far should be sent to subscribers. However, this introduces the need for another thread, requires thread synchronization, and is plain inelegant. Specifying a timeout for BeginRead would also suffice (call back into my code every now and then so I can check if there's data to be sent back; most of the time there will not be anything to do, so I expect the performance hit to be negligible). But it looks like timeouts are not supported in FileStream. Since I imagine that async calls with timeouts are an option in bare Win32, another approach might be to PInvoke the hell out of the problem. But this is also undesirable as it will introduce complexity and simply be a pain to code. Is there an elegant way to get around the problem? Thanks for being patient enough to read all of this.

    Read the article

  • Download pdf programatically...

    - by Perplexed
    Hi, How can I download a pdf and store to disk using vb.net or c#? The url (of the pdf) has some rediection going on before the final pdf is reached. I tried the below but the pdf seems corrupted when I attempt to open locally, Dim PdfFile As FileStream = File.OpenWrite(saveTo) Dim PdfStream As MemoryStream = GetFileStream(pdfURL) PdfStream.WriteTo(PdfFile) PdfStream.Flush() PdfStream.Close() PdfFile.Flush() PdfFile.Close() many thanks, KS

    Read the article

  • Asynchronous operations performance

    - by LicenseQ
    One of the features of asynchronous programming in .NET is saving threads during long running operation execution. The FileStream class can be setup to allow asynchronous operations, that allows running (e.g.) a copy operation without virtually using any threads. To my surprise, I found that running asynchronous stream copy performs not only slower, but also uses more processing power than synchronous stream copy equivalent. Is there any benchmark tests were done to compare a synchronous vs asynchronous operation execution (file, network, etc.)? Does it really make sense to perform an asynchronous operation instead of spanning separate thread and perform synchronous operation in server environment if the asynchronous operation is times slower than the synchronous one?

    Read the article

  • Something like System.Diagnostics.Process.Start to run a stream

    - by phenevo
    Hi, I get from server images and videos by stream. Now I'm saving it: Stream str = client.GetFile(path); using (var outStream = new FileStream(@"c:\myFile.jpg", FileMode.Create)) { var buffer = new byte[4096]; int count; while ((count = str.Read(buffer, 0, buffer.Length)) > 0) { outStream.Write(buffer, 0, count); } } I can be jpg, mpg, flv and a lot of other multimedia types (Before I get stream I know what is a extension of this file). Now I want to not save it , bu run direct from stream. Is it possible ??

    Read the article

  • What is the largest file size we can transfer through air application?

    - by Naveen kumar
    Hi all, I'm trying to transfer large file(1Gb+) using UDP(in packets) through air application. I'm transfering byteArray by taking chunks of packets from FileStream. But its giving 'Error #1000: The system is out of memory' at sender side after certain number of packets sent and by this time the downloaded file size at server side is 256 MB. I tried with other files but after downloading 256MB, sender is giving the same error. Is it because of the file stream size? How can I solve this problem so that I can transfer files of GB size.

    Read the article

  • Programatically find out a file type by looking its binary content. Possible?

    - by daemonkid
    I have a c# component that will recieve a file of the following types .doc, .pdf, .xls, .rtf These will be sent by the calling siebel legacy app as a filestream. So... [LegacyApp] {Binary file stream} [Component] The legacy app is a black box that cant be modified to tell the component what file type (doc,pdf,xls) it is sending. The component needs to read this binary stream and create a file on the filesystem with the right extension. Any ideas? Thanks for your time.

    Read the article

  • Which file types are worth compressing (zipping) for remote storage? For which of them the compresse

    - by user193655
    I am storing documents in sql server in varbinary(max) fileds, I use filestream optionally when a user has: (DB_Size + Docs_Size) ~> 0.8 * ExpressEdition_Max_DB_Size I am currently zipping all the files, anyway this is done because the Document Read/Write work was developed 10 years ago where Storage was more expensive than now. Many files when zipped are almost as big as the original (a zipped pdf is about 95% of original size). And anyway unzipping has some overhead, that becomes twice when I need also to "Check-in"/Update the file because I need to zip it. So I was thinking of giving to the users the option to choose whether the file type will be zipped or not by providing some meaningful default values. For my experience I would impose the following rules: 1) zip by default: txt, bmp, rtf 2) do not zip by default: jpg, jpeg, Microsoft Office files, Open Office files, png, tif, tiff Could you suggest other file types chosen among the most common or comment on the ones I listed here?

    Read the article

  • [C#] Lock a file and avoid readings while it's writing

    - by vtortola
    Hi, My web application returns a file from the filesystem. These files are dynamic, so I have no way to know the names o how many of them will there be. When this file doesn't exist, the application creates it from the database. I want to avoid that two different threads recreate the same file at the same time, or that a thread try to return the file while other thread is creating it. So I want to lock a file till its recreation is complete, if other thread try to access it ... it will have to wait the file be unlocked. I've been reading about FileStream.Lock, but I have to know the file length and it won't prevent that other thread try to read the file, so it doesn't work for my particular case. I've been reading also about FileAccess.None, but it will throw an exception (which exception type?) if other thread/process try to access the file... so I should develop a "try again while is faulting" ... and I don't like too much that approach, although maybe there is not a better way. How could I archieve this? Kind regards.

    Read the article

  • How to Lock a file and avoid readings while it's writing

    - by vtortola
    My web application returns a file from the filesystem. These files are dynamic, so I have no way to know the names o how many of them will there be. When this file doesn't exist, the application creates it from the database. I want to avoid that two different threads recreate the same file at the same time, or that a thread try to return the file while other thread is creating it. So I want to lock a file till its recreation is complete, if other thread try to access it ... it will have to wait the file be unlocked. I've been reading about FileStream.Lock, but I have to know the file length and it won't prevent that other thread try to read the file, so it doesn't work for my particular case. I've been reading also about FileAccess.None, but it will throw an exception (which exception type?) if other thread/process try to access the file... so I should develop a "try again while is faulting" ... and I don't like too much that approach, although maybe there is not a better way.

    Read the article

  • MultipartFormDataContent Access to patch xx is denied

    - by Florian Schaal
    So I'm trying to upload a pdf file to a restapi. For some reason I the application cant get access to the files on my pc. The code im using to upload: public void Upload(string token, string FileName, string FileLocation, string Name, int TypeId, int AddressId, string CompanyName, string StreetNr, string Zip, string City, string CountryCode, string CustomFieldName, string CustomFieldValue) { var client = new HttpClient(); client.BaseAddress = _API.baseAddress; //upload a new form client.DefaultRequestHeaders.Date = DateTime.Now; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token); using (var multiPartContent = new MultipartFormDataContent()) { //get te bytes from a file byte[] pdfData; using (var pdf = new FileStream(@FileLocation, FileMode.Open))//Here i get the error. { pdfData = new byte[pdf.Length]; pdf.Read(pdfData, 0, (int)pdf.Length); } var fileContent = new ByteArrayContent(pdfData); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = FileName + ".pdf" }; //add the bytes to the multipart message multiPartContent.Add(fileContent); //make a json message var json = new FormRest { Name = Name, TypeId = TypeId, AddressId = AddressId, CompanyName = CompanyName, StreetNr = StreetNr, Zip = Zip, City = City, CountryCode = CountryCode, CustomFields = new List<CustomFieldRest> { new CustomFieldRest {Name = CustomFieldName, Value = CustomFieldValue} } }; var Content = new JsonContent(json); //add the json message to the multipart message multiPartContent.Add(Content); var result = client.PostAsync("forms", multiPartContent).Result; } } }

    Read the article

  • how do i insert html file that have hebrew text and read it back in sql server 2008 using the filest

    - by gadym
    hello all, i am new to the filestream option in sql server 2008, but i have already understand how to open this option and how to create a table that allow you to save files. let say my table contains: id,name, filecontent i tried to insert an html file (that has hebrew chars/text in it) to this table. i'm writing in asp.net (c#), using visual studio 2008. but when i tried to read back the content , hebrew char becomes '?'. the actions i took were: 1. i read the file like this: // open the stream reader System.IO.StreamReader aFile = new StreamReader(FileName, System.Text.UTF8Encoding.UTF8); // reads the file to the end stream = aFile.ReadToEnd(); // closes the file aFile.Close(); return stream; // returns the stream i inserted the 'stream' to the filecontent column as binary data. i tried to do a 'select' to this column and the data did return (after i coverted it back to string) but hebrew chars become '?' how do i solve this problem ? what I should pay attention to ? thanks, gadym

    Read the article

  • Extracting, then passing raw data into another class - How to avoid copying twice while maintaining

    - by Kache4
    Consider a class Book with a stl container of class Page. each Page holds a screenshot, like page10.jpg in raw vector<char> form. A Book is opened with a path to a zip, rar, or directory containing these screenshots, and uses respective methods of extracting the raw data, like ifstream inFile.read(buffer, size);, or unzReadCurrentFile(zipFile, buffer, size). It then calls the Page(const char* stream, int filesize) constructor. Right now, it's clear that the raw data is being copied twice. Once to extract to Book's local buffer and a second time in the Page ctor to the Page::vector<char>. Is there a way to maintain encapsulation while getting rid of the middleman buffer?

    Read the article

  • django return file over HttpResonse - file is not served correctly

    - by Tom Tom
    I want to return some files in a HttpResponse and I'm using the following function. The file that is returned always has a filesize of 1kb and I do not know why. I can open the file, but it seems that it is not served correctly. Thus I wanted to know how one can return files with django/python over a HttpResponse. @login_required def serve_upload_files(request, file_url): import os.path import mimetypes mimetypes.init() try: file_path = settings.UPLOAD_LOCATION + '/' + file_url fsock = open(file_path,"r") #fsock = open(file_path,"r").read() file_name = os.path.basename(file_path) mime_type_guess = mimetypes.guess_type(file_name) try: if mime_type_guess is not None: response = HttpResponse(mimetype=mime_type_guess[0]) response['Content-Disposition'] = 'attachment; filename=' + file_name response.write(fsock) finally: fsock.close() except IOError: response = HttpResponseNotFound() return response

    Read the article

  • PushbackReader without EOF?!

    - by Frank
    Hello SOers, I'm currently using PushbackReader and while waiting for where it 'supposed' to be an EOF, I get the character 65535 and I'm wondering if that's normal. Where is my EOF?! Thank you.

    Read the article

  • Load binary file using fstream

    - by Kirill V. Lyadvinsky
    I'm trying to load binary file using fstream in the following way: #include <iostream #include <fstream #include <iterator #include <vector using namespace std; int main() { basic_fstream<uint32_t file( "somefile.dat", ios::in|ios::binary ); vector<uint32_t buffer; buffer.assign( istream_iterator<uint32_t, uint32_t( file ), istream_iterator<uint32_t, uint32_t() ); cout << buffer.size() << endl; return 0; } But it doesn't work. In Ubuntu it crashed with std::bad_cast exception. In MSVC++ 2008 it just prints 0. I know that I could use file.read to load file, but I want to use iterator and operator>> to load parts of the file. Is that possible? Why the code above doesn't work?

    Read the article

  • Comparing file contents in F#

    - by Bartosz Milewski
    I wrote a quick and dirty function to compare file contents (BTW, I have already tested that they are of equal size): let eqFiles f1 f2 = let bytes1 = Seq.ofArray (File.ReadAllBytes f1) let bytes2 = Seq.ofArray (File.ReadAllBytes f2) let res = Seq.compareWith (fun x y -> (int x) - (int y)) bytes1 bytes2 res = 0 I'm not happy with reading the whole contents into an array. I'd rather have a lazy sequence of bytes, but I can't find the right API in F#.

    Read the article

  • Check if file is locked or catch error for trying to open

    - by Duncan Matheson
    I'm trying to handle the problem where a user can try to open, with an OpenFileDialog, a file that is open by Excel. Using the simple FileInfo.OpenRead(), it chucks an IOException, "The process cannot access the file 'cakes.xls' because it is being used by another process." This would be fine to display to the user except that the user will actually get "Debugging resource strings are unavailable" nonsense. It seems not possible to open a file that is open by another process, since using FileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite) chucks a SecurityException, "File operation not permitted. Access to path 'C:\whatever\cakes.xls' is denied.", for any file. Rather unhelpful. So it's down to either finding some way of checking if the file is locked, or trying to catch the IOException. I don't want to catch all IOExceptions and assume they're all locked file errors, so I need some sort of way of classifying this type of exception as this error... but the "Debugging resource strings" nonsense along with the fact that that message itself is probably localized makes it tricky. I'm partial trust, so I can't use Marshal.GetHRForException. So: Is there any sensible way of either check if a file is locked, or at least determining if this problem occurred without just catching all IOExceptions?

    Read the article

  • StreamWriter stops writing when file is opened from web link

    - by fearofawhackplanet
    Following on from my previous question... The following code creates log files on a web server: private void LogMessage(Message msg) { using (StreamWriter sw = File.AppendText(_logDirectory + DateTime.Now.ToString("yyyyMMddHH") + ".txt")) { sw.WriteLine(msg.ToString()); } } The log files are linked to from an admin page on the web site: foreach (FileInfo file in logDir.GetFiles()) { Response.Write("<a href='http:// .... /Logs/" + file.Name + "'>" + file.Name + "</a>"); } I'm getting the problem that after someone looks at one of the log files from the link, that log file stops being written to.

    Read the article

  • StreamWriter not creating new file

    - by fearofawhackplanet
    I'm trying to create a new log file every hour with the following code running on a server. The first log file of the day is being created and written to fine, but no further log files that day get created. Any ideas what might be going wrong? No exceptions are thrown either. private void LogMessage(Message msg) { using (StreamWriter sw = File.AppendText(_logDirectory + DateTime.Today.ToString("yyyyMMddHH") + ".txt")) { sw.WriteLine(msg.ToString()); } }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >