Click here to Skip to main content
15,899,023 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I am creating a code which uses streamwriter to create a new text file each time it is run, it puts all UI from textboxes into a text file. my issue is... in my code i have a textbox which is set to a code that converts all input (ascii) to hex and writes the hex values to text file, (I have set parameters to the textbox to accept only alpha-numeric values, and to only accept upto 27 characters). I need for any characters not filled by the user (up to 27) to be replaced by a 0, but need the (extra) 0 to be written to the text file and not turned to hex. I can only think to overwrite, but how to overwrite a file which is in the process of being created.

I have put the basic part of my code that applies parameters to UI, and converts input to hex, which is then written to a new text file which is created by the code.

Many thanks in advance for any suggestions

Fazila

What I have tried:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Ascii_to_hex
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            
        }
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (!char.IsControl(e.KeyChar) && !char.IsLetterOrDigit(e.KeyChar))
                {
                    e.Handled = true;
                }
            }

        private void button2_Click(object sender, EventArgs e)
        {
            System.IO.StreamWriter objWriter;
            string name = label1.Text;
            objWriter = new System.IO.StreamWriter(name + ".inp");


            string str = textBox2.Text;
            char[] charValues = str.ToCharArray();
            string hexOutput = "";
            foreach (char _eachChar in charValues)
            {
                                                             
                int value = Convert.ToInt32(_eachChar);
                                                        
                hexOutput += String.Format("{0:X}", value);
                                                          
            }

            objWriter.WriteLine(hexOutput);

            objWriter.Close();
        }
Posted
Updated 6-Nov-18 19:42pm

hexOutput = hexOutput.PadRight( 27, '0' );
objWriter.WriteLine(hexOutput);
 
Share this answer
 
Here's some ideas you could adapt:
using System;
using System.Linq;

namespace YourConverionLibrary
{
    public static class ConversionExtensions
    {
        public static byte[] ToByteAry(this string input, bool filterforAlpha = true)
        {
            if (filterforAlpha)
            {
                input = new string(input.Where(c => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c)).ToArray());
            }

            return input.Select(c => (byte) c).ToArray();
        }

        public static string ToHxFrmBytAry(this byte[] input)
        {
            return BitConverter.ToString(input);
        }
    }
}
Sample usage:
var test = "testing 1 2 3 !".ToByteAry().ToHxFrmBytAry();
Console.WriteLine(test);
The string generated:

74-65-73-74-69-6E-67-20-31-20-32-20-33-20

note the final ! char is excluded, but the final space is included.
 
Share this answer
 
v2
Comments
Richard Deeming 7-Nov-18 8:15am    
I'd be inclined to make ToByteAry take an IEnumerable<char> instead of a string. That way, you can avoid creating a new string to filter out unwanted characters.

You'll also have problems with characters outside of the standard ASCII range. It would probably be better to use System.Text.Encoding.Default.GetBytes, which will handle these properly.

public static byte[] ToByteAry(this IEnumerable<char> input, bool filterforAlpha = true)
{
    if (filterforAlpha)
    {
        input = input.Where(c => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c));
    }
    	
    return Encoding.Default.GetBytes(input.ToArray());
}
BillWoodruff 7-Nov-18 14:47pm    
"I'd be inclined to make ToByteAry take an IEnumerable<char> instead of a string." The OP is using the contents of a TextBox as a source: using a string extension method makes sense to me.

"You'll also have problems with characters outside of the standard ASCII range." Why ?

I assert that my code reflects what the OP wants to do, even if it's not good enough for you :)
Richard Deeming 16-Nov-18 12:11pm    
Just seen this - did you miss the "Reply" button, or was it one of the many recent QA bugs? :)

String implements IEnumerable<char>; and if you make the parameter IEnumerable<char>, you can filter it without having to create a new temporary string to hold the filtered values.

A char is equivalent to a ushort. If the input string contains characters outside of the range 0-255, the cast to byte will either overflow (in an unchecked context), or throw an OverflowException (in a checked context). The OP mentioned restricting the input to alpha-numeric values, so it may not be a problem for them. I just though it was worth mentioning.
BillWoodruff 16-Nov-18 22:15pm    
Hi Richard, Of course I clicked 'Reply: how else would the messager appear as a response ? Did you not get a notification ?

I'll study your response later today, and, I am sure I will learn from it.

Are you saying the code could be better, or, are you saying there's a bug in it ?
Richard Deeming 19-Nov-18 8:09am    
The notifications have been messing around for a while now. :)

IEnumerable<char> vs string is just a minor performance tweak. But since Encoding.GetBytes requires an array, I'm not sure how much difference, if any, it would make. I just prefer to avoid allocating new strings if it can be avoided.

The Encoding.GetBytes vs casting each character to a byte could potentially be a small bug-ette, depending on how the value will be used, and whether the value will ever contain non-ASCII characters. For example, if the intention was to convert it back to the original string, you couldn't do that if the cast had overflowed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900