C# Connect via SSH and changing the file content - c#

I am a C # amateur I am not a professional developer and would like to ask my colleagues for help, I would like to make a C # program that connects to an SSH server. Then, depending on the selected value in combobox, the program downloads the appropriate string and I would like to send it to the ssh server to the specified path path and save the value from the string to the file;)
I tried to rewrite the code but something did not work out and I stopped in my place ;( Can anyone help me. Thanks in advance for your help.
this is my code
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;
using System.Threading;
using Renci.SshNet;
namespace FileGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
SshClient sshClient = new SshClient("192.168.1.22", 22, "root", "pass");
sshClient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(120);
sshClient.Connect();
ShellStream shellStreamSSH = sshClient.CreateShellStream("vt-100", 80, 60, 800, 600, 65536);
Thread thread = new Thread(() => recvSSHData(shellStreamSSH));
thread.Start();
//I don't know how to get the information if it is connected correctly and change e.g. btnConnect label to Connected.
}
public static void recvSSHData(ShellStream shellStreamSSH)
{
while (true)
{
try
{
if (shellStreamSSH != null && shellStreamSSH.DataAvailable)
{
string strData = shellStreamSSH.Read();
}
}
catch
{
}
System.Threading.Thread.Sleep(200);
}
}
string data1 = "data1";
string data2 = "data2";
string data3 = "data3";
string check;
string path = "/home/test01/desktop";
string filename = "test.txt";
private void btnSend_Click(object sender, EventArgs e)
{
if (cmbData.SelectedIndex == 0)
{
check = data1;
MessageBox.Show(check);
}
else if (cmbData.SelectedIndex == 1)
{
check = data2;
MessageBox.Show(check);
}
else if (cmbData.SelectedIndex == 2)
{
check = data3;
MessageBox.Show(check);
}
else
{
MessageBox.Show("Choose a value");
}
//And now there should be an instruction that sends a string check to the server to path to file replacing its contents
}
}
}

Ok, I coped with everything but I am on the last step, how to save the contents of string to a file using client scp ??
string text= "bal bla bla bla bla"
string path = "#/home/test01/desktop/";
string filename = "test1.txt"
...
try
{
MemoryStream mStrm = new MemoryStream(Encoding.UTF8.GetBytes(text));
scpClient.Upload(mStrm, path + filename);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I have error:
Renci.SshNet.Common.ScpException: scp: error: unexpected filename:
w Renci.SshNet.ScpClient.CheckReturnCode(Stream input)
w Renci.SshNet.ScpClient.UploadFileModeAndName(IChannelSession channel, Stream input, Int64 fileSize, String serverFileName)
w Renci.SshNet.ScpClient.Upload(Stream source, String path)
w FileGenerator.Form1.btnSend_Click(Object sender, EventArgs e) w C:\Users\backu\source\repos\FileGenerator\FileGenerator\Form1.cs:wiersz 192

Related

Incorrect reading of an array

I am working in c-sharp .net and I am working on creating a login screen for my project. I have a text file with login info for all the users. My c-sharp scrip reads that file to a string then cuts it up into two lists, _usernames and _passwords. When the user types their login info and hits login the _usernames[0] and _passwords[0] account info are the only ones that work. What I want it to do is look through all the _usernames for the inputted one, if it finds it then check the _password[same index as _usernames] and if both are the same as what the user submitted then it will add "true" to the richTextBox.
Why is it not correctly reading from the array?
This is my users.txt:
admin,test|
andrew,yeet|
zana,happy|
This is my c-sharp script:
using System;
using System.IO;
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 BaseUserInterfase
{
public partial class Login : Form
{
string path = Directory.GetCurrentDirectory() + "\\data\\users.txt";
string data;
string[] _usernames = new string[10];
string[] _passwords = new string[10];
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
GetLoginData();
}
private void btnLogin_Click(object sender, EventArgs e)
{
rtbTemp.Text = "";
for(int i = 0; i < _usernames.Length; i++)
{
if(_usernames[i] == null)
{
break;
}
rtbTemp.AppendText("\n" + _usernames[i]);
rtbTemp.AppendText("\n" + tbUsername.Text.ToString());
rtbTemp.AppendText("\n" + _passwords[i]);
rtbTemp.AppendText("\n" + tbPassword.Text.ToString());
if (_usernames[i] == tbUsername.Text.ToString())
{
rtbTemp.AppendText("\nUsername true");
if (_passwords[i] == tbPassword.Text.ToString())
{
rtbTemp.AppendText("\nPassword true");
rtbTemp.AppendText("\ntrue");
return;
}
}
}
rtbTemp.AppendText("\nfalse");
}
public void GetLoginData()
{
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{
data = streamReader.ReadToEnd();
}
List<string> _data = data.Split('|').ToList();
_data.RemoveAt(_data.Count - 1);
rtbTemp.AppendText("\n");
Array.Resize<string>(ref _usernames, _data.Count);
Array.Resize<string>(ref _passwords, _data.Count);
foreach (string _item in _data)
{
List<string> userdata = _item.Split(',').ToList();
string username = userdata[0].ToString();
string password = userdata[1].ToString();
Console.WriteLine(_item);
Console.WriteLine(username);
Console.WriteLine(password);
for(int i = 0; i < _data.Count; i++)
{
if(_usernames[i] == null)
{
_usernames[i] = username;
_passwords[i] = password;
break;
}
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
And this is an image of the login screen:
1
Your file contains carriage return characters. Remove them before you split its content
data = streamReader.ReadToEnd().Replace("\r\n", "");

Access to file denied in C# .NET 3.1 forms

Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
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;
using System.IO;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.

AudioSwitcher API change output device

I made a small gadget with an Arduino that sends 2 values via serial to my c# program (potentiometer value for volume and switch button to change output device). The volume part is already complete but I'm not being able to change between the two output devices (monitor audio and Headphones).
My code at the moment:
using AudioSwitcher.AudioApi.CoreAudio;
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 Volume
{
public partial class Form1 : Form
{
//msg recieved by serial
String msg;
string[] tokens;
//active device
CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice;
String PHONES = "Headphones (Razer Kraken USB)";
String COLUNA = "ASUS VP228-4 (NVIDIA High Definition Audio)";
public Form1()
{
//open port for serial msg and start timmer
InitializeComponent();
serialPort1.Open();
timer1.Enabled = true;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
//handling of the msg
msg = serialPort1.ReadLine();
tokens = msg.Split('%');
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = tokens[0];
label2.Text = tokens[1];
label6.Text = defaultPlaybackDevice.FullName;
//change volume
defaultPlaybackDevice.Volume = Int32.Parse(tokens[0]);
//change output device
if (tokens[1] == "ON")
{
if (defaultPlaybackDevice.FullName == PHONES)
{
//do nothing
}
else
{
//change to monitor output
}
}
else
{
if (defaultPlaybackDevice.FullName == COLUNA)
{
//do nothing
}
else
{
//change to headphones
}
}
}
}
}
I am using an API called AudioSwitcher.AudioApi.CoreAudio which should allow me to do what I want but I am not being able to find how.
First you need to get all the PlaybackDevices
IEnumerable<CoreAudioDevice> devices = new CoreAudioController().GetPlaybackDevices();
and then you can make a function to change your Default playbackdevice with the fullname like this
private void ChangeOutput(string op)
{
foreach (CoreAudioDevice d in devices)
{
if (d.FullName == op)
d.SetAsDefault();
}
}

No Book Results from ISBNDB with Valid ISBN

I've got a weird issue here. I'll start by explaining my program:
I have a C# application. The main goal of the program is to get information about a book based on its ISBN. The ISBN is passed to the program via a TCP/IP scanner on an Android device. The ISBN is then put into a valid URL which is used to grab the XML data from ISBNDB.com.
The issue that I am having is this:
When I query an ISBN typed into a TextBox, the program works fine. When I query an ISBN scanned from the reader, it returns 'No Results'
I have implemented various ways to try and get to the bottom of this case. Right before the XML is read, I have a message box show me the XML that it received:
As you can see, it shows no results. However, when I visit the URL (Also gotten from within the program):
I get this in Microsoft Edge:
Which, is exactly what I would think the application would get as well.
Does anyone know what is going on? If so, what can I do to fix it and how can my code be improved to eliminate this error?
For those interested, here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Threading;
using System.Diagnostics;
namespace LibraryBookLister
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string XML = "";
private void btnQuery_Click(object sender, EventArgs e)
{
GetXMLBarcodeData();
}
private void GetXMLBarcodeData()
{
string Barcode4 = textBarcode.Text;
MessageBox.Show(Barcode4);
string barcode = Barcode4;
StringBuilder output = new StringBuilder();
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
// Set the reader settings object to use the resolver.
if(barcode.Length > 13)
{
barcode = barcode.Remove(14);
MessageBox.Show(barcode);
}
string xmlString = #"?access_key=IDC057UX&results=details&index1=isbn&value1=" + barcode;
MessageBox.Show("GEttting book info for : " + barcode);
Uri baseUri = new Uri("https://isbndb.com/api/books.xml");
Uri fulluri = resolver.ResolveUri(baseUri, xmlString);
MessageBox.Show("Now Getting The URL: " + fulluri.ToString());
Process.Start(fulluri.ToString());
StringBuilder sb = new StringBuilder();
XmlReader readesr = XmlReader.Create(fulluri.ToString());
MessageBox.Show("REading data from " + fulluri.ToString());
while (readesr.Read())
{
sb.AppendLine(readesr.ReadOuterXml());
}
string XMLs = sb.ToString();
XML = XMLs;
MessageBox.Show("XML : " + XML);
GetXMLStuff();
}
public void GetXMLStuff()
{
tcplistener.Stop();
XmlDocument doc = new XmlDocument();
doc.LoadXml(XML);
XmlNodeList nodes = doc.DocumentElement.SelectNodes("/ISBNdb/BookList");
List<Book> books = new List<Book>();
foreach (XmlNode node in nodes)
{
Book book = new Book();
try
{
if (node.SelectSingleNode("BookData/AuthorsText").InnerText == null)
{
MessageBox.Show("Could not find this book. Please enter data by hand.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
textBarcode.Clear();
return;
}
}
catch
{
MessageBox.Show("Could not find this book. Please enter data by hand.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
// textBarcode.Clear();
return;
}
book.author = node.SelectSingleNode("BookData/AuthorsText").InnerText;
book.title = node.SelectSingleNode("BookData/Title").InnerText;
book.ISBN = node.SelectSingleNode("BookData").Attributes["isbn"].Value;
books.Add(book);
MessageBox.Show(book.author);
addInfo(book.author, book.title, book.ISBN);
textBarcode.Clear();
}
// MessageBox.Show("Total books: " + books.Count);
}
private void addInfo(string Author, string Title, string ISBN)
{
textAuthor.Text = Author;
textTitle.Text = Title;
textISBN.Text = ISBN;
}
class Book
{
public string ISBN;
public string title;
public string author;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
int time = 10;
bool cancel = false;
private void timer1_Tick(object sender, EventArgs e)
{
if(time > 0)
{
labelTime.Text = time.ToString();
button1.Text = "Change Data";
cancel = true;
labelTime.Visible = true;
time--;
// MessageBox.Show(time.ToString());
}
if(time <= 0)
{
cancel = false;
button1.Text = "Add to List";
timer1.Stop();
time = 10;
labelTime.Visible = false;
MessageBox.Show("Submitting");
}
}
private void button1_Click(object sender, EventArgs e)
{
if(cancel)
{
timer1.Stop();
labelTime.Visible = false;
time = 10;
cancel = false;
button1.Text = "Add to List";
}
else
{
timer1.Start();
}
}
private void button2_Click(object sender, EventArgs e)
{
Thread tcpServer = new Thread(new ParameterizedThreadStart(TCPServerRun));
//TCPServerRun();
tcpServer.Start();
}
bool on = true;
TcpListener tcplistener = new TcpListener(IPAddress.Any, 5004);
private void TCPServerRun(object test)
{
try
{
MessageBox.Show("Starting Listener");
tcplistener.Start();
}
catch { MessageBox.Show("COULDNT START TPCSERVER"); return; }
while (on == true)
{
try
{
TcpClient client = tcplistener.AcceptTcpClient();
Thread tcpHandlerThread = new Thread(new ParameterizedThreadStart(tcpHandler));
// tcpHandlerThread.Start(client);
tcpHandler(client);
}
catch
{
tcplistener.Stop();
// MessageBox.Show("Stopping Listener");
}
}
}
string bCode = "";
private void tcpHandler(object client)
{
TcpClient mClient = (TcpClient)client;
NetworkStream stream = mClient.GetStream();
byte[] message = new byte[1024];
stream.Read(message, 0, message.Length);
bCode = Encoding.ASCII.GetString(message);
stream.Close();
mClient.Close();
MessageBox.Show(bCode);
this.textBarcode.Text = bCode;
GetXMLBarcodeData();
}
}
}
Possible Hint: Could it have something to do with how I have threads working?
*Edit: * **I have updated the code to have the barcode be put in a textBox and then used to fetch the data. This does not seem to work either because it 'Cannot access the control on a thread other than on which it was created'
If manual user input succeed while automated input fail, the simplest hack is just replacing the automated input to a call to manual control BeginInvoke. For your code this would be :
textBarcode.BeginInvoke(new Action(() => {
textBarcode.Text = bCode;
GetXMLBarcodeData();
}));

How can i check if a text file contain more then one line of text inside?

I have this code:
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
}
Once im running the program it will do: Logger.Write(items);
Then the text file will look like:
Danie hello
Ron hi
Yael bye
Josh everyone ok
Next time im running the program it will write to the text file the same strings.
I want to check if this string already exist in the text file dont write them again else do write so the result will be that each time im running the program it will write to the logger(text file) only new strings if there are any.
This is the string variable of the logger text file:
full_path_log_file_name
This variable inside have:
C:\\Users\\Chocolade\\AppData\\Local\\ChatrollLogger\\ChatrollLogger\\log\\logger.txt
This is the complete code untill this part wich is the part that DoWork always do one time when im running the program:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using DannyGeneral;
namespace ChatrollLogger
{
public partial class Form1 : Form
{
string log_file_name = #"\logger.txt";
string full_path_log_file_name;
string path_log;
bool result;
List<string> namesAndTexts;
WebResponse response;
StreamReader reader;
string profileName;
string profileNameText;
string url;
string testingUrl;
int index;
List<string> names;
List<string> texts;
WebClient wc;
public Form1()
{
InitializeComponent();
Logger.exist();
wc = new WebClient();
result = true;
url = "http://chatroll.com/rotternet";
testingUrl = "http://chatroll.com/testings";
backgroundWorker1.RunWorkerAsync();
path_log = Path.GetDirectoryName(Application.LocalUserAppDataPath) + #"\log";
full_path_log_file_name = path_log + log_file_name;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
List<string> tempNamesAndTexts = new List<string>();
string tempDownload = downloadContent();
GetProfileNames(tempDownload);
GetTextFromProfile(tempDownload);
for (int i = 0; i < names.Count; i++)
{
tempNamesAndTexts.Add(names[i] + " " + texts[i]);
}
if (InvokeRequired)
{
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
string t = full_path_log_file_name;
}
}
Something like this?
string path = "test.txt";
string valueToWrite = "....";
//only write to the file, if the specified string is not already there
if(!File.ReadLines(path).Any(l => string.Equals(l, valueToWrite)))
{
File.AppendAllText(path, valueToWrite);
}
Use File.ReadAllLines
string[] array = File.ReadAllLines("test.txt");
if(array.Length > 0)
{
// lines exist
}

Categories

Resources