I have a strange problem. I wrote a .net 2.0 console application running on Windows Server 2008 R2 that processes a file that's passed in via args When I run it by hand and pass in a file, I don't get an output. Nothing. No errors or exception of any kind. Event log is clear. I would expect that I get some output from the exe. I also have a Console.WriteLine in my catch statement. But again, no output whatsoever. Any ideas why?
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.IO;
namespace RTDXCentralFileTransmit
{
class Program
{
static void Main(string[] args)
{
try
{
if (args.Length < 1)
{
Console.WriteLine("File name is required");
logit("File name is required");
return;
}
string filename = args[0];
Console.WriteLine("Now doing " + filename);
logit("Now doing " + filename);
if (!File.Exists(filename))
{
Console.WriteLine("File " + filename + " does not exists. Exiting.");
logit("File " + filename + " does not exists. Exiting.");
File.WriteAllText("Error.txt", "File " + filename + " does not exists. Exiting.");
return;
}
string fileplain = File.ReadAllText(filename);
string file64 = EncodeTo64(fileplain);
if (string.IsNullOrEmpty(file64))
{
Console.WriteLine("File " + filename + " is empty. Exiting");
logit("File " + filename + " is empty. Exiting");
File.WriteAllText("Error.txt", "File " + filename + " is empty. Exiting");
return;
}
FileInfo fi = new FileInfo(filename);
com.xxxxxxxxxxxxxxxxxx.api.Dispatch dis = new com.xxxxxxxxxxxxxxxx.api.Dispatch();
com.xxxxxxxxxxxx.api.FunnelResult fr = dis.Funnel(file64, fi.Name);
if (fr.Success)
{
Console.WriteLine("Success! " + fr.Result);
logit("Success! Response from the server: " + fr.Result);
File.WriteAllText("Success.txt", fr.Result);
return;
} else
{
Console.WriteLine("Failed!! " + fr.Result);
logit("Failed!! " + fr.Result);
File.WriteAllText("Error.txt", "Transmission Failed! " + fr.Result);
}
logit("Exiting for " + filename);
Environment.Exit(0);
} catch (Exception e)
{
Console.WriteLine("Error. " + e.ToString());
return;
}
}
static void logit (string s)
{
File.AppendAllText("FileTransmit.log",DateTime.Now.ToString() + ":" + s + Environment.NewLine);
}
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
}
}
I found it. The issue was between the chair and the computer.
The project that I cloned, even though it had tons of Console.WriteLine, it was actually was being built as Windows Application. That explains why we have no output for the Console.WriteLine.
Since it was being build as windows application, the console doesn't wait for the program to finish. It returns right away - which totally threw me off seeing that many console.writelines. However, the program is still running and, with a large file, it takes a while to post it to the remote server. After waiting a minute or two all of 10 MB file was transmitted successfully as it was indicated in the logs.
Related
I have created a code to create folders with two Textboxes.
Textbox1 - customer number (XXXX).
Textbox2 - customer name.
I would like to be able to check if the customer number exists before creating the folder.
The newly created folder will be the combination of the two Textboxes (this is already solved).
I just need to be able to determine if the folder exists only with the customer number, as it is probably created with (customer number + customer name).
Current working code:
{
string no = textBox1.Text;
string client = textBox2.Text;
string carpeta = #"C:\" + no + " " + client;
string sourcePath = #"C:\main";
string destinationPath = #"C:\" + no + " " + client;
textBox1.Clear();
textBox2.Clear();
try
{
if (Directory.Exists(carpeta))
{
DialogResult y;
y = MessageBox.Show("Folder already exists\nDo you want to open it?", "AE.", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (y == DialogResult.Yes)
{
System.Diagnostics.Process.Start(#"C:\" + no + " " + client);
}
else
{
Close();
}
}
else
{
DialogResult x;
x = MessageBox.Show("The folder doesn't exist\nWant to create a folder?." + "\n" + no + " " + client, "AE.", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (x == DialogResult.Yes)
{
Directory.CreateDirectory(carpeta);
FileSystem.CopyDirectory(sourcePath, destinationPath, UIOption.AllDialogs);
System.Diagnostics.Process.Start(#"C:\" + no + " " + client);
}
else
{
Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message);
}
}
You could also each time you need the folder just do that:
public static void Main()
{
var username = "someuser";
var usernumber = "ABC123";
var mainDirectory = #"C:\Path\To\The\Main\Dir";
var pathToTheUserDirectory = Path.Combine(mainDirectory, $"{username}-{usernumber}");
// This line will create the directory if not exist or take the existing directory.
var directoryInfo = Directory.CreateDirectory(pathToTheUserDirectory);
var directoryPath = directoryInfo.FullName;
// ...
// or
// directoryInfo.Delete(recursive: true);
}
string[] dirs = Directory.GetDirectories(#"c:\", txtTextBox.Text + "*");
this will only get directrories starting with the desired Text
Edit: This is only a good solution if the customer number has fixed places (in you exaple 4 from 0000-9999)
Microsoft Documentation - check example below
I am getting an error when I run this newFile method:
class logFile
{
public static string logpath = #"D:\Program Files\CustomApps\DataFeed\";
public static void log(string log)
{
string timestamp = DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss");
Console.WriteLine(timestamp + log);
File.AppendAllText(logpath + #"log_file_current.txt", timestamp + log + Environment.NewLine);
}
public static void newFile()
{
if (File.Exists(logpath + #"log_file_current.txt") == true)
{
File.Move(logpath + #"log_file_current.txt"
, logpath + #"log_files\log_file_ORPHANED_" + DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss") + ".txt");
}
try
{
File.Create(logpath + #"log_file_current.txt");
logFile.log("logFile created.");
}
catch(System.NotSupportedException ex)
{
Console.WriteLine(ex.Message);
}
}
}
I get the following error:
If I comment the body of the "newFile" code out then it runs without error, but then I would need to manually archive. If I comment out the File.Move part it all runs fine so this is the culprit.
How can I release the file so that it can be moved?
You need to use File.Close after using File.Create, this is why you are getting an error saying the file is used by another process. Try adding this line to your code :
try
{
File.Create(logpath + #"log_file_current.txt").Close(); // Notice the .Close() here
logFile.log("logFile created.");
}
Source : Closing a file after File.Create
Try this one
public static void log(string log)
{
string timestamp = DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss") + ": ";
Console.WriteLine(timestamp + log);
using (StreamWriter sw = File.AppendText(logpath + #"log_file_current.txt"))
{
sw.WriteLine(timestamp + log);
}
}
I made script task that's downloading and saving on disk two spreadsheets from Google Drive using file ID and prepared URL address.
This is main() from my C# code, there are no things outside of it:
public void Main()
{
string m_FileId = Dts.Variables["User::varFileId"].Value.ToString();
string m_RemoteUrl = "https://docs.google.com/spreadsheets/d/" + m_FileId + "/export?format=xlsx";
string m_FilePath = null;
WebClient client = new WebClient();
try
{
m_FilePath = Dts.Variables["User::varFilePath"].Value.ToString() + Dts.Variables["User::varFileName"].Value.ToString();
client.DownloadFile(new System.Uri(m_RemoteUrl), m_FilePath);
m_FilePath = "";
m_FileId = Dts.Variables["User::varFileId2"].Value.ToString();
m_RemoteUrl = "https://docs.google.com/spreadsheets/d/" + m_FileId + "/export?format=xlsx";
m_FilePath = Dts.Variables["User::varFilePath"].Value.ToString() + Dts.Variables["User::varFileName2"].Value.ToString();
client.DownloadFile(new System.Uri(m_RemoteUrl), m_FilePath);
}
catch(Exception e)
{
Dts.Events.FireError(0, "FileDownload", e.Message
+ "\r" + e.StackTrace
+ " \rUrl: " + m_RemoteUrl
+ " \rFilePath: " + m_FilePath
+ " \rPath: " + Dts.Variables["User::varFilePath"].Value.ToString()
+ " \rFileName2: " + Dts.Variables["User::varFileName2"].Value.ToString()
, string.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
Dts.TaskResult = (int)ScriptResults.Success;
}
Problem occurs exactly on every second time I run this code and I don't know how to get rid of it. There's just exception in my script task. I'm printing all variables that are used in this code, and as you can see there's something wrong with m_FilePath, it's like multiplied despite of being printed just once.
[FileDownload] Error: An exception occurred during a WebClient request.
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at ST_84b63d1593dd449886eb2b32dff40b2d.ScriptMain.Main()
Url: https://docs.google.com/spreadsheets/d/----------/export?format=xlsx
FilePath: C:\Google Drive extract\ga_manual_cost_file.xlsxC:\Google Drive extract\ga_manual_cost_file.xlsx
Path: C:\Google Drive extract\ga_manual_cost_file.xlsx
FileName2: ga_manual_cost_file.xlsx
SSIS variables that I'm using are ReadOnly, and are used only in this script task(I tried running only this part of control flow), and their values are as follows:
I am creating application to delete files for more than 15 days in past, I've created a project using the C# language "multithreading" to be able to delete these files, but its only reading the first file with the error
The directory name is invalid
Can anyone help me on this please?
private void process3()
{
//DirectoryInfo info1 = new DirectoryInfo(#"\\10.4.9.202\d\PapyrusRes\appdata\");
DirectoryInfo info1 = new DirectoryInfo(#"\\DXB-RASO-MCH\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2");
// long Size = 0;
//C:\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2
String[] filePaths = (from fls in info1.EnumerateFiles()
where (fls.LastWriteTime.Date < DateTime.Today.AddDays(-15))
select fls.FullName).ToArray();
int i = 0;
if (!File.Exists(logPath3))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(logPath3))
{
sw.WriteLine("Deletion Process History:");
sw.WriteLine(" ");
sw.WriteLine(" ");
}
}
//stopwatch.Start();
try
{
foreach (String f in filePaths)
{
DirectoryInfo info = new DirectoryInfo(f);
int difference = DateTime.Today.Subtract(info.LastWriteTime).Days;
textBox2.BeginInvoke(new Action(() =>
{
textBox2.Text += "Folder Name: " + Path.GetFileName(f) +
"\r\nDate Modified: " + difference +
"\r\n------\r\n";
}));
Thread.Sleep(10);
i++;
Directory.Delete(f, true);
count++;
}
using (StreamWriter sw = File.AppendText(logPath3))
{
sw.WriteLine("Successful at: " + DateTime.Now + " " + count +
" files were deleted");
}
}
catch (Exception ex)
{
// log errors
// Write your content here
using (StreamWriter sw = File.AppendText(logPath3))
{
if (count == 0)
sw.WriteLine("Unsuccessful at: " + DateTime.Now + " Error: " +
ex.Message);
else
sw.WriteLine("Unsuccessful at: " + DateTime.Now + " " + count +
" files were deleted" + " Error: " + ex.Message);
}
}
}
Don't Know What's wrong but I can't Access even It created a directory.. This is my code
private void btnRegister_Click(object sender, EventArgs e)
{
try
{
var sw = new System.IO.StreamWriter("E:Praisey\\" + txtAcc.Text + "\\Login.ID");
sw.Write(txtAcc.Text + "\n" + txtZipCode.Text);
sw.Close();
}
catch(System.IO.DirectoryNotFoundException ex)
{
System.IO.Directory.CreateDirectory("E:Praisey\\" + txtAcc.Text + "\\Login.ID");
var sw = new System.IO.StreamWriter("E:Praisey\\" + txtAcc.Text + "\\Login.ID");
sw.Write(txtAcc.Text + "\n" + txtZipCode.Text);
sw.Close();
}
}
it always getting error! The error is
UnauthorizedAccessException was unhandled
Access to the path 'E:\Praisey\48492995\Login.ID' is denied.
As I see from your catch block, "E:Praisey\\" + txtAcc.Text + "\\Login.ID" is actually a directory. You must also add the file name to the path.
var sw = new System.IO.StreamWriter("E:Praisey\\" + txtAcc.Text + "\\Login.ID\\filename.txt");
This error occurs (had it yesterday too) when the Directory does not exist. You need to create it before starting your StreamWriter.
if (!Directory.Exists("E:Praisey\\" + txtAcc.Text))
Directory.CreateDirectory("E:Praisey\\" + txtAcc.Text);