Search Results

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

Page 16/19 | < Previous Page | 12 13 14 15 16 17 18 19  | Next Page >

  • Instantiating a list of parameterized types, making beter use of Generics and Linq

    - by DanO
    I'm hashing a file with one or more hash algorithms. When I tried to parametrize which hash types I want, it got a lot messier than I was hoping. I think I'm missing a chance to make better use of generics or LINQ. I also don't like that I have to use a Type[] as the parameter instead of limiting it to a more specific set of type (HashAlgorithm descendants), I'd like to specify types as the parameter and let this method do the constructing, but maybe this would look better if I had the caller new-up instances of HashAlgorithm to pass in? public List<string> ComputeMultipleHashesOnFile(string filename, Type[] hashClassTypes) { var hashClassInstances = new List<HashAlgorithm>(); var cryptoStreams = new List<CryptoStream>(); FileStream fs = File.OpenRead(filename); Stream cryptoStream = fs; foreach (var hashClassType in hashClassTypes) { object obj = Activator.CreateInstance(hashClassType); var cs = new CryptoStream(cryptoStream, (HashAlgorithm)obj, CryptoStreamMode.Read); hashClassInstances.Add((HashAlgorithm)obj); cryptoStreams.Add(cs); cryptoStream = cs; } CryptoStream cs1 = cryptoStreams.Last(); byte[] scratch = new byte[1 << 16]; int bytesRead; do { bytesRead = cs1.Read(scratch, 0, scratch.Length); } while (bytesRead > 0); foreach (var stream in cryptoStreams) { stream.Close(); } foreach (var hashClassInstance in hashClassInstances) { Console.WriteLine("{0} hash = {1}", hashClassInstance.ToString(), HexStr(hashClassInstance.Hash).ToLower()); } }

    Read the article

  • Read binary file into a struct C#

    - by Robert Höglund
    I'm trying to read binary data using C#. I have all information about the layout of the data in the files I want to read. I'm able to read the data "chunk by chunk", i.e. getting the first 40 bytes of data converting it to a string, get the next 40 bytes, ... Since there are at least three slighlty different version of the data, I would like to read the data directly into a struct. It just feels so much more right than by reading it "line by line". I have tried the following approach but to no avail:StructType aStruct; int count = Marshal.SizeOf(typeof(StructType)); byte[] readBuffer = new byte[count]; BinaryReader reader = new BinaryReader(stream); readBuffer = reader.ReadBytes(count); GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType)); handle.Free(); The stream is an opened FileStream from which I have began to read from. I get an AccessViolationException when using Marshal.PtrToStructure. The stream contains more information than I'm trying to read since I'm not interested in data at the end of the file. The struct is defined like:[StructLayout(LayoutKind.Explicit)] struct StructType { [FieldOffset(0)] public string FileDate; [FieldOffset(8)] public string FileTime; [FieldOffset(16)] public int Id1; [FieldOffset(20)] public string Id2; } The examples code is changed from original to make this question shorter. How would I read binary data from a file into a struct?

    Read the article

  • C# File IO with Streams - Best Memory Buffer Size

    - by AJ
    Hi, I am writing a small IO library to assist with a larger (hobby) project. A part of this library performs various functions on a file, which is read / written via the FileStream object. On each StreamReader.Read(...) pass, I fire off an event which will be used in the main app to display progress information. The processing that goes on in the loop is vaired, but is not too time consuming (it could just be a simple file copy, for example, or may involve encryption...). My main question is: What is the best memory buffer size to use? Thinking about physical disk layouts, I could pick 2k, which would cover a CD sector size and is a nice multiple of a 512 byte hard disk sector. Higher up the abstraction tree, you could go for a larger buffer which could read an entire FAT cluster at a time. I realise with today's PC's, I could go for a more memory hungry option (a couple of MiB, for example), but then I increase the time between UI updates and the user perceives a less responsive app. As an aside, I'm eventually hoping to provide a similar interface to files hosted on FTP / HTTP servers (over a local network / fastish DSL). What would be the best memory buffer size for those (again, a "best-case" tradeoff between perceived responsiveness vs. performance). Thanks in advance for any ideas, Adam

    Read the article

  • Creating a shim Stream

    - by spender
    A decompression API that I am using has the following API: Decode(Stream inStream,Stream outStream) I'd like to create a wrapper around this API, such that I can create my own Stream class which offers up the decoded data. Stream decodedStream=new BlaDecodeStream(inStream); So that I can than use this stream as a parameter to the XmlReader constructor in the same way one might use the System.IO.Compression.GZipStream. As far as I can tell, the only other option is set outStream stream to a MemoryStream or to a FileStream and go in two hops. The files I am dealing with are enormous, so neither of these options are particularly attractive. Before I go reinventing the wheel, is there any prior art that I might be able to draw from, or something in the BCL I might have missed? The CircularStream implementation here would go some of the way to helping, but I'm really looking for something similar that would block (as opposed to over/underrun) when the Stream's internal buffer is 'empty' when reading from it and block when the internal buffer is full when writing to it. In this way it could serve as parameter outStream and simultaneously (i.e. from another thread) could be read from by the XmlReader.

    Read the article

  • How to compile a schema that uses a DataSet (xs:schema)?

    - by Yaron Naveh
    I have created the simplest web service in c#: public void AddData(DataSet ds) The generated schema (Wsdl) looks like this: <s:schema xmlns:s="http://www.w3.org/2001/XMLSchema"> ... <s:element ref="s:schema" /> ... </s:schema> Note the schema does not contain any import/include elements. I am trying to load this schema to a c# System.Xml.XmlSchema and add it to System.Xml.XmlSchemaSet: var set = new XmlSchemaSet(); var fs = new FileStream(@"c:\temp\schema.xsd", FileMode.Open); var s = XmlSchema.Read(fs, null); set.Add(s); set.Compile(); The last line throws this exception: The 'http://www.w3.org/2001/XMLSchema:schema' element is not declared. It kind of makes sense: The schema generated by .Net uses the "s:schema" type which is declared in a schema which is not imported. Why does .Net create a non valid schema? How to compile the schema anyway? Whay I did is download the schema in http://www.w3.org/2001/XMLSchema and added it to the XmlSchemaSet also. This did not work since that online schema contains DTD definition. I had to manually remove it and now all works. Does this make sense or am I missing something?

    Read the article

  • Rotate and Save Image - C#

    - by Taylor
    Hello, I'm trying to rotate and save an image, along with returning a BitmapSource. I pass in the rotation value (90 or -90) and the full path to the image I want to rotate to the method shown here. It works fine if I start and stop my application between calling this method. however, if the application calls rotate multiple times the rotate only happens once. I know the original image must be cached in memory, because if I pass values 90, 180, 270 I see the rotations work. I want to be able to pass in a value of 90 or -90 and have that rotate and save the original image. How can I make the rotate work for each call? Is there a way to clear the cached value of the image? If I don't set the BitmapCacheOption to OnLoad, I am unable to transform and save the image since the image is "being used by another process". public BitmapImage Rotate(int val, string path) { //create a new image from existing file. Image image = new Image(); BitmapImage logo = new BitmapImage(); logo.BeginInit(); logo.CacheOption = BitmapCacheOption.OnLoad; logo.UriSource = new Uri(path); logo.EndInit(); image.Source = logo; BitmapSource img = (BitmapSource)(image.Source); //rotate image and save CachedBitmap cache = new CachedBitmap(img, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); TransformedBitmap tb = new TransformedBitmap(cache, new RotateTransform(val)); TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(tb)); using (FileStream file = File.OpenWrite(path)) { encoder.Save(file); } //update page view BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.UriSource = new Uri(path); bi.EndInit(); return bi; }

    Read the article

  • Error "Input length must be multiple of 8 when decrypting with padded cipher"

    - by Ross Peoples
    I am trying to move a project from C# to Java for a learning exercise. I am still very new to Java, but I have a TripleDES class in C# that encrypts strings and returns a string value of the encrypted byte array. Here is my C# code: using System; using System.IO; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; namespace tDocc.Classes { /// <summary> /// Triple DES encryption class /// </summary> public static class TripleDES { private static byte[] key = { 110, 32, 73, 24, 125, 66, 75, 18, 79, 150, 211, 122, 213, 14, 156, 136, 171, 218, 119, 240, 81, 142, 23, 4 }; private static byte[] iv = { 25, 117, 68, 23, 99, 78, 231, 219 }; /// <summary> /// Encrypt a string to an encrypted byte array /// </summary> /// <param name="plainText">Text to encrypt</param> /// <returns>Encrypted byte array</returns> public static byte[] Encrypt(string plainText) { UTF8Encoding utf8encoder = new UTF8Encoding(); byte[] inputInBytes = utf8encoder.GetBytes(plainText); TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider(); ICryptoTransform cryptoTransform = tdesProvider.CreateEncryptor(key, iv); MemoryStream encryptedStream = new MemoryStream(); CryptoStream cryptStream = new CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write); cryptStream.Write(inputInBytes, 0, inputInBytes.Length); cryptStream.FlushFinalBlock(); encryptedStream.Position = 0; byte[] result = new byte[encryptedStream.Length]; encryptedStream.Read(result, 0, (int)encryptedStream.Length); cryptStream.Close(); return result; } /// <summary> /// Decrypt a byte array to a string /// </summary> /// <param name="inputInBytes">Encrypted byte array</param> /// <returns>Decrypted string</returns> public static string Decrypt(byte[] inputInBytes) { UTF8Encoding utf8encoder = new UTF8Encoding(); TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider(); ICryptoTransform cryptoTransform = tdesProvider.CreateDecryptor(key, iv); MemoryStream decryptedStream = new MemoryStream(); CryptoStream cryptStream = new CryptoStream(decryptedStream, cryptoTransform, CryptoStreamMode.Write); cryptStream.Write(inputInBytes, 0, inputInBytes.Length); cryptStream.FlushFinalBlock(); decryptedStream.Position = 0; byte[] result = new byte[decryptedStream.Length]; decryptedStream.Read(result, 0, (int)decryptedStream.Length); cryptStream.Close(); UTF8Encoding myutf = new UTF8Encoding(); return myutf.GetString(result); } /// <summary> /// Decrypt an encrypted string /// </summary> /// <param name="text">Encrypted text</param> /// <returns>Decrypted string</returns> public static string DecryptText(string text) { if (text == "") { return text; } return Decrypt(Convert.FromBase64String(text)); } /// <summary> /// Encrypt a string /// </summary> /// <param name="text">Unencrypted text</param> /// <returns>Encrypted string</returns> public static string EncryptText(string text) { if (text == "") { return text; } return Convert.ToBase64String(Encrypt(text)); } } /// <summary> /// Random number generator /// </summary> public static class RandomGenerator { /// <summary> /// Generate random number /// </summary> /// <param name="length">Number of randomizations</param> /// <returns>Random number</returns> public static int GenerateNumber(int length) { byte[] randomSeq = new byte[length]; new RNGCryptoServiceProvider().GetBytes(randomSeq); int code = Environment.TickCount; foreach (byte b in randomSeq) { code += (int)b; } return code; } } /// <summary> /// Hash generator class /// </summary> public static class Hasher { /// <summary> /// Hash type /// </summary> public enum eHashType { /// <summary> /// MD5 hash. Quick but collisions are more likely. This should not be used for anything important /// </summary> MD5 = 0, /// <summary> /// SHA1 hash. Quick and secure. This is a popular method for hashing passwords /// </summary> SHA1 = 1, /// <summary> /// SHA256 hash. Slower than SHA1, but more secure. Used for encryption keys /// </summary> SHA256 = 2, /// <summary> /// SHA348 hash. Even slower than SHA256, but offers more security /// </summary> SHA348 = 3, /// <summary> /// SHA512 hash. Slowest but most secure. Probably overkill for most applications /// </summary> SHA512 = 4, /// <summary> /// Derrived from MD5, but only returns 12 digits /// </summary> Digit12 = 5 } /// <summary> /// Hashes text using a specific hashing method /// </summary> /// <param name="text">Input text</param> /// <param name="hash">Hash method</param> /// <returns>Hashed text</returns> public static string GetHash(string text, eHashType hash) { if (text == "") { return text; } if (hash == eHashType.MD5) { MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA1) { SHA1Managed hasher = new SHA1Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA256) { SHA256Managed hasher = new SHA256Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA348) { SHA384Managed hasher = new SHA384Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA512) { SHA512Managed hasher = new SHA512Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.Digit12) { MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider(); string newHash = ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); return newHash.Substring(0, 12); } return ""; } /// <summary> /// Generates a hash based on a file's contents. Used for detecting changes to a file and testing for duplicate files /// </summary> /// <param name="info">FileInfo object for the file to be hashed</param> /// <param name="hash">Hash method</param> /// <returns>Hash string representing the contents of the file</returns> public static string GetHash(FileInfo info, eHashType hash) { FileStream hashStream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read); string hashString = ""; if (hash == eHashType.MD5) { MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA1) { SHA1Managed hasher = new SHA1Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA256) { SHA256Managed hasher = new SHA256Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA348) { SHA384Managed hasher = new SHA384Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA512) { SHA512Managed hasher = new SHA512Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } hashStream.Close(); hashStream.Dispose(); hashStream = null; return hashString; } /// <summary> /// Converts a byte array to a hex string /// </summary> /// <param name="data">Byte array</param> /// <returns>Hex string</returns> public static string ByteToHex(byte[] data) { StringBuilder builder = new StringBuilder(); foreach (byte hashByte in data) { builder.Append(string.Format("{0:X1}", hashByte)); } return builder.ToString(); } /// <summary> /// Converts a hex string to a byte array /// </summary> /// <param name="hexString">Hex string</param> /// <returns>Byte array</returns> public static byte[] HexToByte(string hexString) { byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i <= returnBytes.Length - 1; i++) { returnBytes[i] = byte.Parse(hexString.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } return returnBytes; } } } And her is what I've got for Java code so far, but I'm getting the error "Input length must be multiple of 8 when decrypting with padded cipher" when I run the test on this: import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import com.tdocc.utils.Base64; public class TripleDES { private static byte[] keyBytes = { 110, 32, 73, 24, 125, 66, 75, 18, 79, (byte)150, (byte)211, 122, (byte)213, 14, (byte)156, (byte)136, (byte)171, (byte)218, 119, (byte)240, 81, (byte)142, 23, 4 }; private static byte[] ivBytes = { 25, 117, 68, 23, 99, 78, (byte)231, (byte)219 }; public static String encryptText(String plainText) { try { if (plainText.isEmpty()) return plainText; return Base64.decode(TripleDES.encrypt(plainText)).toString(); } catch (Exception e) { e.printStackTrace(); } return null; } public static byte[] encrypt(String plainText) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchPaddingException { try { final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(ivBytes); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = plainText.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); return cipherText; } catch (Exception e) { e.printStackTrace(); } return null; } public static String decryptText(String message) { try { if (message.isEmpty()) return message; else return TripleDES.decrypt(message.getBytes()); } catch (Exception e) { e.printStackTrace(); } return null; } public static String decrypt(byte[] message) { try { final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(ivBytes); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, iv); final byte[] plainText = cipher.doFinal(message); return plainText.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } }

    Read the article

  • How to determine the size (in bytes) of a file downloading using NSURLConnection?

    - by RexOnRoids
    I need to know the size of the file I am downloading (in bytes) into my app using NSURLConnection (GET). Here is my bytes recieved code below if it helps. What I need to know is how to get the filesize in bytes so that I can use it to show a UIProgressView. - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data // A delegate method called by the NSURLConnection as data arrives. We just // write the data to the file. { #pragma unused(theConnection) NSInteger dataLength; const uint8_t * dataBytes; NSInteger bytesWritten; NSInteger bytesWrittenSoFar; assert(theConnection == self.connection); dataLength = [data length]; dataBytes = [data bytes]; bytesWrittenSoFar = 0; do { bytesWritten = [self.fileStream write:&dataBytes[bytesWrittenSoFar] maxLength:dataLength - bytesWrittenSoFar]; assert(bytesWritten != 0); if (bytesWritten == -1) { [self _stopReceiveWithStatus:@"File write error"]; break; } else { bytesWrittenSoFar += bytesWritten; } while (bytesWrittenSoFar != dataLength); }

    Read the article

  • Can't hit breakpoint in ASP.NET web app (Stop debugging in progress... popup in VS)

    - by dotnetdev
    Hi, I am trying to debug some code in my ASP.NET web app. I set a breakpoint in one of the page events of the page's codebehind, and this once came up with a special icon in place of the red breakpoint saying symbols have not been loaded and the breakpoint will not be hit. This error has not repeated itself but why can't I hit the breakpoint? Also, when I press stop, I get a popup in VS stating: Stop Debugging In Progres... Debugging is being stopped but is not yet complete. You can force debugging to stop completely, but any processes attached may terminate. This window will automatically close when debugging has completely stopped. Completely stop I also don't get the website appear in my browser either when starting to debug. :( To make things worse, I have a line of code like this in my page's codebehind: RssFeedSites = opml.Parse(filestream); I am putting the problematic breakpoint on this line. But I have a programatic breakpoint in the Parse() method of opml, but this does not get hit, either. Thanks

    Read the article

  • Creating files with french characters and encoding.

    - by Kevin
    HI, I am creating a file like so. FileStream temp = File.Create( this.FileName ); Then putting data in the file like so. this.Writer = new StreamWriter( this.Stream ); this.Writer.WriteLine( strMessage ); That code is encapsulated in a class hierarchy but that is the meat and potatoes of it. My problem is this. MSDN says that the default encoding for creating a file this way is UTF8. And when I write a french character such as é Textpad interprets the file as a UTF 8 file, but notepad++ says it's "ANSI as UTF8" or maybe it's an ansi file but is reading it as UTF8. When I create a file the same way without the french character both textpad and notepad++ read the file as an ansi file even though according to msdn it should be a utf 8 file still. Which program should be trusted. Notepad++ or textpad - Notepad++ seems to be more consistant, but is still the oppossite to what MSDN says it should be. My problem is that we create files that get sent off to another company and depending on whether there are french characters the encoding seems to keep changing. Or is there a better way to determine the encoding of a file. I've read about byte order marks and preambles but as far as I understand neither are guaranteed to be there. We initially thought that all the files we were building were ansi. Also please note that both ansi and utf8 should handle the french characters appropriately as the characters are part of both character sets.

    Read the article

  • Why do I get completely different results when saving a BitmapSource to bmp, jpeg, and png in WPF

    - by DanM
    I wrote a little utility class that saves BitmapSource objects to image files. The image files can be either bmp, jpeg, or png. Here is the code: public class BitmapProcessor { public void SaveAsBmp(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new BmpBitmapEncoder()); } public void SaveAsJpg(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new JpegBitmapEncoder()); } public void SaveAsPng(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new PngBitmapEncoder()); } private void Save(BitmapSource bitmapSource, string path, BitmapEncoder encoder) { using (var stream = new FileStream(path, FileMode.Create)) { encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); encoder.Save(stream); } } } Each of the three Save methods work, but I get unexpected results with bmp and jpeg. Png is the only format that produces an exact reproduction of what I see if I show the BitmapSource on screen using a WPF Image control. Here are the results: BMP - too dark JPEG - too saturated PNG - correct Why am I getting completely different results for different file types? I should note that the BitmapSource in my example uses an alpha value of 0.1 (which is why it appears very desaturated), but it should be possible to show the resulting colors in any image format. I know if I take a screen capture using something like HyperSnap, it will look correct regardless of what file type I save to. Here's a HyperSnap screen capture saved as a bmp: As you can see, this isn't a problem, so there's definitely something strange about WPF's image encoders. Do I have a setting wrong? Am I missing something?

    Read the article

  • Webdev.Webserver has stopped working

    - by Alexander
    When I execute the code saveXML below it generates the error above, why?? using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Xml.Serialization; using System.IO; /// <summary> /// Summary description for Post /// </summary> public class Post { private int postIDCounter = 0; private String DateCreated; public Post() { Author = "unknown"; Title = "unkown"; Content = ""; DateCreated = DateTime.Now.ToString(); ID = postIDCounter++; } public int ID { get { return ID; } set { if (ID != value) ID = value; } } public string Author { get { return Author; } set { if (Author != value) Author = value; } } public string Title { get { return Title; } set { if (Title != value) Title = value; } } public string Content { get { return Content; } set { if (Content != value) Content = value; } } public void saveXML() { XmlSerializer serializer = new XmlSerializer(typeof(Post)); Stream writer = new FileStream("..'\'App_Data'\'posts'\'" + new Guid(ID.ToString()).ToString() + ".xml", FileMode.Create); serializer.Serialize(writer, this); writer.Close(); } }

    Read the article

  • Constant error in compiler using C#'s provided objects

    - by dotnetdev
    I have used the built in C# methods to write a compiler, like the following: CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp"); string Output = "Out.exe"; Button ButtonObject = (Button)sender; this.RadTextBox1.Text = string.Empty; System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(); //Make sure we generate an EXE, not a DLL parameters.GenerateExecutable = true; parameters.OutputAssembly = Output; CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, RadTextBox1.Text); if (results.Errors.Count > 0) { RadTextBox2.ForeColor = Color.Red; foreach (CompilerError CompErr in results.Errors) { RadTextBox2.Text = RadTextBox2.Text + "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } } else { //Successful Compile RadTextBox2.ForeColor = Color.Blue; Guid guid = Guid.NewGuid(); string PathToExe = Server.MapPath(Path.Combine(@"\Compiled" , Output)); FileStream fs = System.IO.File.Create(PathToExe); using (StreamWriter sw = new StreamWriter(fs)) { sw.Write(RadTextBox1.Text); } Response.WriteFile(PathToExe); When I run this code and write a Main method (such as the code sample in http://msdn.microsoft.com/en-us/library/ms228506(VS.80).aspx, I get this error: Line number 0, Error Number: CS5001, 'Program 'c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Out.exe' does not contain a static 'Main' method suitable for an entry point; The code above is used as the basis of a compiler on my site (not yet live). So you type in code and generate an .exe assembly. But when I enter code into the textbox for code writing (Radtextbox1), even with a main method, I get the error. What gives? Thanks

    Read the article

  • Is it possible to store controls(Panel) as object, serialize it and store it as a file?

    - by ikky
    The topic says it all. Using Compact Framework C# I'm tiling (order/sequence is important) some images that i download from an url, into a Panel(each image is a PictureBox). This can be a huge process, and may take some time. Therefor i only want the user to download the images and tile them once. So the next time the user uses the Tile Application, the Panel that was created the first time is already stored in a file and is loaded from that file. So what i want is a method to store a Panel as a file. Is this possible, or do you think i should do it another way? I've tried something like this: BinaryWriter panelStorage = new BinaryWriter(new FileStream("imagePanel.panel", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)); Byte[] bImageObject = new Byte[20000]; bImageObject = (byte[])(object)this.imagePanel; panelStorage .Write(bMapObject); panelStorage .Close(); But the casting was not very legal :P "InvalidCastException" Can anyone help me with this problem? Thank you in advance!

    Read the article

  • Locking behaviour is different via network shares

    - by MattH
    I have been trying to lock a file so that other cloned services cannot access the file. I then read the file, and then move the file when finished. The Move is allowed by using FileShare.Delete. However in later testing, we found that this approach does not work if we are looking at a network share. I appreciate my approach may not have been the best, but my specific question is: Why does the below demo work against the local file, but not against the network file? The more specific you can be the better, as I've found very little information in my searches that indicates network shares behave differently to local disks. string sourceFile = @"C:\TestFile.txt"; string localPath = @"C:\MyLocalFolder\TestFile.txt"; string networkPath = @"\\MyMachine\MyNetworkFolder\TestFile.txt"; File.WriteAllText(sourceFile, "Test data"); if (!File.Exists(localPath)) File.Copy(sourceFile, localPath); foreach (string path in new string[] { localPath, networkPath }) { using (FileStream fsLock = File.Open(path, FileMode.Open, FileAccess.ReadWrite, (FileShare.Read | FileShare.Delete))) { string target = path + ".out"; File.Move(path, target); //This is the point of failure, when working with networkPath if (File.Exists(target)) File.Delete(target); } if (!File.Exists(path)) File.Copy(sourceFile, path); }

    Read the article

  • iTextSharp last version doesnot support metadata?

    - by zp chen
    Console.WriteLine("Chapter 1 example 6: Meta Information"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, new FileStream("Chap0106.pdf", FileMode.Create)); // step 3: we add some metadata and open the document document.AddTitle("Hello World example"); document.AddSubject("This example explains step 6 in Chapter 1"); document.AddKeywords("Metadata, iText, step 6, tutorial"); document.AddCreator("My program using iText#"); document.AddAuthor("Bruno Lowagie"); document.AddHeader("Expires", "0"); document.Open(); // step 4: we add a paragraph to the document document.Add(new Paragraph("Hello World")); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); I am just copy the iTextSharp.tutorial. I get the pdf file Chap0106.pdf but metadata show nothing... I am use vs2008 xp system

    Read the article

  • Using MinHash to find similiarities between 2 images

    - by Sung Meister
    I am using MinHash algorithm to find similar images between images. I have run across this post, How can I recognize slightly modified images? which pointed me to MinHash algorithm. Being a bit mathematically challenged, I was using a C# implementation from this blog post, Set Similarity and Min Hash. But while trying to use the implementation, I have run into 2 problems. What value should I set universe value to? When passing image byte array to HashSet, it only contains distinct byte values; thus comparing values from 1 ~ 256. What is this universe in MinHash? And what can I do to improve the C# MinHash implementation? Since HashSet<byte> contains values upto 256, similarity value always come out to 1. Here is the source that uses the C# MinHash implementation from Set Similarity and Min Hash: class Program { static void Main(string[] args) { var imageSet1 = GetImageByte(@".\Images\01.JPG"); var imageSet2 = GetImageByte(@".\Images\02.TIF"); //var app = new MinHash(256); var app = new MinHash(Math.Min(imageSet1.Count, imageSet2.Count)); double imageSimilarity = app.Similarity(imageSet1, imageSet2); Console.WriteLine("similarity = {0}", imageSimilarity); } private static HashSet<byte> GetImageByte(string imagePath) { using (var fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) using (var br = new BinaryReader(fs)) { //List<int> bytes = br.ReadBytes((int)fs.Length).Cast<int>().ToList(); var bytes = new List<byte>(br.ReadBytes((int) fs.Length).ToArray()); return new HashSet<byte>(bytes); } } }

    Read the article

  • How Can I Generate Equivalent Output Using the CryptoAPI and the .NET Encryption (TripleDESCryptoSer

    - by S. Butts
    I have some C#/.NET code that encrypts and decrypts data using TripleDES encryption. It sticks to the sample code provided at MSDN pretty closely. The encryption piece looks like the following: TripleDESCryptoServiceProvider _desProvider = new TripleDESCryptoServiceProvider(); //bytes for key and initialization vector //keyBytes is 24 bytes of stuff, vectorBytes is 8 bytes of stuff byte[] keyBytes; byte[] vectorBytes; FileStream fStream = File.Open(locationOfFile, FileMode.Create, FileAccess.Write); CryptoStream cStream = new CryptoStream(fStream, _desProvider.CreateEncryptor(keyBytes, vectorBytes), CryptoStreamMode.Write); BinaryWriter bWriter = new BinaryWriter(cStream); //write out encrypted data //raw data is a few bytes of binary information byte[] rawData; bWriter.Write(rawData); With encrypting and decrypting in C#, this all works like a charm. The problem is I need to write a small Win32 utility that will duplicate the encryption above. I have tried several methods using the CryptoAPI, and I simply do not get output that the .NET piece can decrypt, no matter what I do. Can someone please tell me what the equivalent C++ code is that will produce the same output? I am not certain just what methods of the CryptoAPI the .NET functions use to encrypt the data. What options are used, and what method of generating the key is used? Before someone suggests that I just write it in C# anyway, or create some common library bridge for them, those options are unfortunately off the table. It really has to work in Win32 with .NET and without using a DLL. I have some leeway in changing the C# code. I apologize in advance if this is bone-headed, as I am new to encryption.

    Read the article

  • Azure : The process cannot access the file "" because it is being used by another process.

    - by Shantanu
    Hi all, I am trying to get a matlab-compiled exe running on Azure cloud, and for that purpose need to get a v78.zip onto the local storage of the cloud and unzip it, before I can try to run an exe on the cloud. The program works fine when executed locally, but on deployment gives and error at line marked below in the code. The error is : The process cannot access the file 'C:\Resources\directory\cc0a20f5c1314f299ade4973ff1f4cad.WebRole.LocalStorage1\v78.zip' because it is being used by another process. Exception Details: System.IO.IOException: The process cannot access the file 'C:\Resources\directory\cc0a20f5c1314f299ade4973ff1f4cad.WebRole.LocalStorage1\v78.zip' because it is being used by another process. The code is given below: string localPath = RoleEnvironment.GetLocalResource("LocalStorage1").RootPath; Response.Write(localPath + " \n"); Directory.SetCurrentDirectory(localPath); CloudBlob mblob = GetProgramContainer().GetBlobReference("v78.zip"); CloudBlockBlob mbblob = mblob.ToBlockBlob; CloudBlob zipblob = GetProgramContainer().GetBlobReference("7z.exe"); string zipPath = Path.Combine(localPath, "7z.exe"); string matlabPath = Path.Combine(localPath, "v78.zip"); IEnumerable<ListBlockItem> blocklist = mbblob.DownloadBlockList(); BlobStream stream = mbblob.OpenRead(); FileStream fs = File.Create(matlabPath); (Exception occurs here) It'll be great help if someone could tell me where I'm going wrong. Thanks! Shan

    Read the article

  • Status Code from FTPWebRequest GetResponse method

    - by nick
    This is slightly tricky. I am uploading files to FTP asynchronously. After uploading each file I am checking the status of the upload operation for that file. This can be done with StatusCode property of the FtpWebResponse object for that request. The code snippet is as give below. System.IO.FileStream fs = System.IO.File.Open(fileName, System.IO.FileMode.Open); while ((iWork = fs.Read(buf, 0, buf.Length)) > 0) requestStream.Write(buf, 0, iWork); requestStream.Close(); FtpWebResponse wrRet = ((FtpWebResponse)state.Request.GetResponse()); There are about 37 StatusCode values as per msdn. I am unaware as to which of these status code values will assure that the file is uploaded successfully. Some of them I used in my code to check for success are : wrRet.StatusCode == FtpStatusCode.CommandOK wrRet.StatusCode == FtpStatusCode.ClosingData wrRet.StatusCode == FtpStatusCode.ClosingControl wrRet.StatusCode == FtpStatusCode.ConnectionClosed wrRet.StatusCode == FtpStatusCode.FileActionOK wrRet.StatusCode == FtpStatusCode.FileStatus But I am unaware of the rest. I need to be sure about these codes because based on the failure or success of the upload operation I have other dependant operations to be carried out. A wrong condition can affect the remaining code. Another thought that crossed my mind was to simply put the above code into a try..catch and not depend on these status codes. With this I would not be depending on the status codes and assuming that any failure will always be directed to the catch block. Kindly let me know if this is the right way. Thanks in advance.

    Read the article

  • Getting PCM values of WAV files

    - by user2431088
    I have a .wav mono file (16bit,44.1kHz) and im using this code below. If im not wrong, this would give me an output of values between -1 and 1 which i can apply FFT on ( to be converted to a spectrogram later on). However, my output is no where near -1 and 1. This is a portion of my output 7.01214599609375 17750.2552337646 8308.42733764648 0.000274658203125 1.00001525878906 0.67291259765625 1.3458251953125 16.0000305175781 24932 758.380676269531 0.0001068115234375 This is the code which i got from another post Edit 1: public static Double[] prepare(String wavePath, out int SampleRate) { Double[] data; byte[] wave; byte[] sR = new byte[4]; System.IO.FileStream WaveFile = System.IO.File.OpenRead(wavePath); wave = new byte[WaveFile.Length]; data = new Double[(wave.Length - 44) / 4];//shifting the headers out of the PCM data; WaveFile.Read(wave, 0, Convert.ToInt32(WaveFile.Length));//read the wave file into the wave variable /***********Converting and PCM accounting***************/ for (int i = 0; i < data.Length; i += 2) { data[i] = BitConverter.ToInt16(wave, i) / 32768.0; } /**************assigning sample rate**********************/ for (int i = 24; i < 28; i++) { sR[i - 24] = wave[i]; } SampleRate = BitConverter.ToInt16(sR, 0); return data; }

    Read the article

  • Inverted colours in tiff to PDF conversion

    - by spiderdijon
    I'm sure I'm making some kind of silly mistake here, but when converting a tiff file to PDF, the colours become reversed. I can't figure out why. Here's my code: PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Image.pdf", FileMode.Create)); System.Drawing.Bitmap bm = new System.Drawing.Bitmap(@"C:\Temp\338814-00.tif"); int total = bm.GetFrameCount(FrameDimension.Page); document.Open(); PdfContentByte cb = writer.DirectContent; for (int k = 0; k < total; ++k) { bm.SelectActiveFrame(FrameDimension.Page, k); MemoryStream ms = new MemoryStream(); bm.Save(ms, ImageFormat.Tiff); Image img = Image.GetInstance(ms.ToArray()); img.ScalePercent(72f / (float)img.DpiX * 100); img.SetAbsolutePosition(0, 0); cb.AddImage(img); document.NewPage(); } document.Close(); Thanks.

    Read the article

  • Baffled by differences between WPF BitmapEncoders

    - by DanM
    I wrote a little utility class that saves BitmapSource objects to image files. The image files can be either bmp, jpeg, or png. Here is the code: public class BitmapProcessor { public void SaveAsBmp(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new BmpBitmapEncoder()); } public void SaveAsJpg(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new JpegBitmapEncoder()); } public void SaveAsPng(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new PngBitmapEncoder()); } private void Save(BitmapSource bitmapSource, string path, BitmapEncoder encoder) { using (var stream = new FileStream(path, FileMode.Create)) { encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); encoder.Save(stream); } } } Each of the three Save methods work, but I get unexpected results with bmp and jpeg. Png is the only format that produces an exact reproduction of what I see if I show the BitmapSource on screen using a WPF Image control. Here are the results: BMP - too dark JPEG - too saturated PNG - correct Why am I getting completely different results for different file types? I should note that the BitmapSource in my example uses an alpha value of 0.1 (which is why it appears very desaturated), but it should be possible to show the resulting colors in any image format. I know if I take a screen capture using something like HyperSnap, it will look correct regardless of what file type I save to. Here's a HyperSnap screen capture saved as a bmp: As you can see, this isn't a problem, so there's definitely something strange about WPF's image encoders. Do I have a setting wrong? Am I missing something?

    Read the article

  • Passing IDisposable objects through constructor chains

    - by Matt Enright
    I've got a small hierarchy of objects that in general gets constructed from data in a Stream, but for some particular subclasses, can be synthesized from a simpler argument list. In chaining the constructors from the subclasses, I'm running into an issue with ensuring the disposal of the synthesized stream that the base class constructor needs. Its not escaped me that the use of IDisposable objects this way is possibly just dirty pool (plz advise?) for reasons I've not considered, but, this issue aside, it seems fairly straightforward (and good encapsulation). Codes: abstract class Node { protected Node (Stream raw) { // calculate/generate some base class properties } } class FilesystemNode : Node { public FilesystemNode (FileStream fs) : base (fs) { // all good here; disposing of fs not our responsibility } } class CompositeNode : Node { public CompositeNode (IEnumerable some_stuff) : base (GenerateRaw (some_stuff)) { // rogue stream from GenerateRaw now loose in the wild! } static Stream GenerateRaw (IEnumerable some_stuff) { var content = new MemoryStream (); // molest elements of some_stuff into proper format, write to stream content.Seek (0, SeekOrigin.Begin); return content; } } I realize that not disposing of a MemoryStream is not exactly a world-stopping case of bad CLR citizenship, but it still gives me the heebie-jeebies (not to mention that I may not always be using a MemoryStream for other subtypes). It's not in scope, so I can't explicitly Dispose () it later in the constructor, and adding a using statement in GenerateRaw () is self-defeating since I need the stream returned. Is there a better way to do this? Preemptive strikes: yes, the properties calculated in the Node constructor should be part of the base class, and should not be calculated by (or accessible in) the subclasses I won't require that a stream be passed into CompositeNode (its format should be irrelevant to the caller) The previous iteration had the value calculation in the base class as a separate protected method, which I then just called at the end of each subtype constructor, moved the body of GenerateRaw () into a using statement in the body of the CompositeNode constructor. But the repetition of requiring that call for each constructor and not being able to guarantee that it be run for every subtype ever (a Node is not a Node, semantically, without these properties initialized) gave me heebie-jeebies far worse than the (potential) resource leak here does.

    Read the article

  • Memorystream and Large Object Heap

    - by Flo
    I have to transfer large files between computers on via unreliable connections using WCF. Because I want to be able to resume the file and I don't want to be limited in my filesize by WCF, I am chunking the files into 1MB pieces. These "chunk" are transported as stream. Which works quite nice, so far. My steps are: open filestream read chunk from file into byet[] and create memorystream transfer chunk back to 2. until the whole file is sent My problem is in step 2. I assume that when I create a memory stream from a byte array, it will end up on the LOH and ultimately cause an outofmemory exception. I could not actually create this error, maybe I am wrong in my assumption. Now, I don't want to send the byte[] in the message, as WCF will tell me the array size is too big. I can change the max allowed array size and/or the size of my chunk, but I hope there is another solution. My actual question(s): Will my current solution create objects on the LOH and will that cause me problem? Is there a better way to solve this? Btw.: On the receiving side I simple read smaller chunks from the arriving stream and write them directly into the file, so no large byte arrays involved.

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19  | Next Page >