c# path to file change after using mapimailmessage - c#

There is a strange behaviour that i dont understand.
There'the part of the code wich is imply in my problem.
public static NpgsqlConnection ConnectRead()
{
string pass = "password_here";
StreamReader sr = new StreamReader(#"Stc.cts");
string line;
string conn = "";
while ((line = sr.ReadLine()) != null)
{
conn = line;
}
sr.Close();
conn = Cdf.Cdf.Crypt.Decrypt(conn, pass);
NpgsqlConnection con = new NpgsqlConnection(conn);
con.Open();
return con;
}
and
if (mailCheckBox.Checked == true)
{
string subject = pototal;
string body = "Voici le bon de commande";
MapiMailMessage message = new MapiMailMessage(subject, body);
//message.Files.Add(serveur + nomfichier);
message.Files.Add(#"c:\pdftemp\" + nomfichier);
message.ShowDialog();
}
As you can see, the first part is a connection string and the second one is a mapi to open default mail software.
My problem is: If i dont use the mapi portion of my program, everything work perfectly. If i use the mapi portion, my program stop connecting because it seems to change the Stc.cts path to c:/foxmail/Stc.cts.
If anyone have a clue, i would realy appreciate.

It appears as though your code is using a relative path. You should provide an absolute path in case something changes the "current" directory.
For example, if your file is in the same path as your executable, you could do this:
string strAppDir = Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
// or...
// string strAppDir = AppDomain.CurrentDomain.BaseDirectory;
string strFullPathToMyFile = System.IO.Path.Combine(strAppDir, "Stc.cts");
StreamReader sr = new StreamReader(strFullPathToMyFile);

Related

How to read resources csv file

I used to use csv file in my application
here is the original code
string csvFile = Directory.GetCurrentDirectory() + #"\data\" + Scheme + ".csv"
DataTable dt = ReadCSV(csvFile);
dgv.DataSource = dt;
now I want to put csv file as embedded resource
I tried this. but It does not work
string csvFile = System.Resources.MyFile; //This is error
DataTable dt = ReadCSV(csvFile);
dgv.DataSource = dt;
I wonder how to get the code running correctly?
Once the file has been added in the menu Project/Properties/Resources like #dr.null said, you have to click on the item's name in the solution explorer so that you can set Action property to "build-in resource".
Then, use something like that:
using System.Reflection;
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "assembly_name.Resources.yourFile.csv";
var lines = ReadLines(() => Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName), Encoding.UTF8).ToList();
Where:
public IEnumerable<string> ReadLines(Func<Stream> streamProvider, Encoding encoding)
{
using (var stream = streamProvider())
using (var reader = new StreamReader(stream, encoding))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
You'll have the variable lines containing your csv data.

I am unable to read content from .txt file using StreamReader class of c#

Here is my code..I am trying to read data from .txt file which was stored in music folder. But i am getting some error like,
System.NotSupportedException.
The given path's format is not supported.
Please help...........
string path = #"Music:\streamfile.txt";
using (StreamReader sr = File.OpenText(path))
{
String s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
Console.ReadLine();
There is a list with 'special' folders somewhere but you can construct it yourself:
string path = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"),
"Music", "streamfile.txt");
you can try Environment.GetFolderPath
//if you want windows common music folder ex:C:\Users\Public\Music\streamfile.txt
var CommonMusicPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonMusic) + #"\streamfile.txt";
//if you want windows user music folder ex:C:\Users\username\Music\streamfile.txt
var MyUserMusicPath = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) + #"\streamfile.txt";
using (StreamReader sr = File.OpenText(MyUserMusicPath))
{
String s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
Console.ReadLine();

SSIS 2015 Script task convert text file to UTF8 in C# or VB

I want to convert my resulting txt file into a UTF8 formatted file so I can load it into my Azure SQL DW via Polybase. It is required the source file be in UTF8.
MSDN has an "IO Streaming example" HERE works perfectly for a single job. I am trying to architect an SSIS solution for around 30 tables though. I believe using this method would cause a race condition where the PS script will be locked by 1 SSIS package when another SSIS package needs it.
I am a sql dev, not a .NET dev so please forgive me. How would one convert the above to an SSIS C# Script task assuming I know how to pass parameters into the Script task?
PowerShell Code from MSDN
#Static variables
$ascii = [System.Text.Encoding]::ASCII
$utf16le = [System.Text.Encoding]::Unicode
$utf8 = [System.Text.Encoding]::UTF8
$ansi = [System.Text.Encoding]::Default
$append = $False
#Set source file path and file name
$src = [System.IO.Path]::Combine("<MySrcFolder>","<MyUtf8stage>.txt")
#Set source file encoding (using list above)
$src_enc = $ascii
#Set target file path and file name
$tgt = [System.IO.Path]::Combine("<MyDestFolder>","<MyFinalstage>.txt")
#Set target file encoding (using list above)
$tgt_enc = $utf8
$read = New-Object System.IO.StreamReader($src,$src_enc)
$write = New-Object System.IO.StreamWriter($tgt,$append,$tgt_enc)
while ($read.Peek() -ne -1)
{
$line = $read.ReadLine();
$write.WriteLine($line);
}
$read.Close()
$read.Dispose()
$write.Close()
$write.Dispose()
Update
I found a similar post which I was able to tweak to my needs, I swear I searched high and low before posting. Anyway here is what IS working for me. If you see anyway to improve it please share:
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;
Your code indicates that your are trying to convert an ASCII file to UTF-8 however that article also states the following:
As UTF-8 uses the same character encoding as ASCII PolyBase will also
support loading data that is ASCII encoded.
So my advice to you is to try the file first with Polybase, check for any conversion issues before you spend any time trying to convert the files.
var mySrcFolder = ""; // something from user variables?
var myUtf8stage = ""; // something from user variables?
var myFinalstage = ""; // something from user variables?
// Static variables
var ascii = System.Text.Encoding.ASCII;
var utf16le = System.Text.Encoding.Unicode;
var utf8 = System.Text.Encoding.UTF8;
var ansi = System.Text.Encoding.Default;
var append = false;
// Set source file path and file name
var src = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myUtf8stage));
// Set source file encoding (using list above)
var src_enc = ascii;
// Set target file path and file name
var tgt = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myFinalstage));
// Set target file encoding (using list above)
var tgt_enc = utf8;
using (var read = new System.IO.StreamReader(src, src_enc))
using (var write = new System.IO.StreamWriter(tgt, append, tgt_enc))
{
while (read.Peek() != -1)
{
var line = read.ReadLine();
write.WriteLine(line);
}
}
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;

File cannot be accessed because it is being used by another process

I'm kind of new to coding and I've been trying to replace a word in a text file but when I execute the program it gives me the "File is used by another process error"
private void btnSave1_Click(object sender, EventArgs e)
{
string DOB = dateTimePicker1.Value.ToString();
string Fname = txtBFirstName.ToString();
string Lname = txtBLastName.ToString();
string IDnum = txtBIDnum.ToString();
string Address = txtBAddress.ToString();
string nationality = txtBNationality.ToString();
//string gender = cmbGender.SelectedItem.ToString();
// string marrStatus = cmbMaritialStatus.SelectedItem.ToString();
StreamReader read = null;
//write to file
try
{
// var lines = File.ReadAllLines("CV.txt");
string line;
read = new StreamReader("CurriculumVitae.txt");
while ((line = read.ReadLine()) != null)
{
string text = File.ReadAllText("CurriculumVitae.txt");
text = text.Replace("Empty", DOB);
File.WriteAllText("CurriculumVitae.txt",
File.ReadAllText("CurriculumVitae.txt")
.Replace("empty",DOB));
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
read.Close();
}
//Open Next Form
Education objNextForm = new Education();
objNextForm.Visible = true;
}
Problem from these 3 lines
read = new StreamReader("CurriculumVitae.txt");
string text = File.ReadAllText("CurriculumVitae.txt");
File.WriteAllText("CurriculumVitae.txt"
,File.ReadAllText("CurriculumVitae.txt").Replace("empty",DOB));
Both StreamReader and File.ReadAllText will lock a file. And whenever they try to lock same file it will error
You should try to do thing once. Don't try to open file many times. And don't open same file before it closed
You can just take out this part around your code, as you're not using the StreamReader you created:
while ((line = read.ReadLine()) != null)
{
...
}
And change
File.WriteAllText("CurriculumVitae.txt",
File.ReadAllText("CurriculumVitae.txt");
To
File.WriteAllText("CurriculumVitae.txt", text);
You will want to update your StreamReader to open the file in "shared" mode so that it doesn't lock the file.
See this question for details on how to do that.
First, don't use a StreamReader when you use File.ReadAllText as it's not needed, the other error comes from this line:
File.WriteAllText("CurriculumVitae.txt", File.ReadAllText("CurriculumVitae.txt").Replace("empty", DOB));
You are opening the same file twice, try something like this:
string content = File.ReadAllText("CurriculumVitae.txt").Replace("empty", DOB);
File.WriteAllText("CurriculumVitae.txt", content);
Use either StreamReader or ReadAllText but not both at the same time...
Also I would really suggest to do "usings" wherever possible becuase this helps a lot closing objects (but is not your prime problem here)
// It will free resources on its own.
//
using (StreamReader reader = new StreamReader("file.txt"))
{
line = reader.ReadLine();
}
Console.WriteLine(line);
}

Download a .srt file with the information in a database table

I'm making this website to download subtitles. Right now I have this function to upload:
using (StreamReader sr = new StreamReader(file.InputStream, Encoding.Default, true))
{
string line;
while ((line = sr.ReadLine()) != null)
{
srtContent += line + '\0';
}
}
SubtitleFile item = new SubtitleFile();
UpdateModel(item);
item.state = State.Edit;
item.SubtitleText = srtContent;
item.name = char.ToUpper(item.name[0]) + item.name.Substring(1);
repo.AddSubtitle(item);
repo.Save();
ModelState.Clear();
And this uploads the srtContent to a place in my databse called SubtitleText,
Now I somehow need to be able to download this again.
So far I only have a hyperlink to a View that I call Downloader,
But that's all I got so far for the downloader.
What I'm missing is a way to take the information of ID given and do some sort of streamwriter or something, and put the info back into a new file where it would be something like
Model.name + '.srt'
with all the same text as I originally copied.
Hopefully I made this understandable. All constructive help appriciated.
Given that the information is stored in a database, we're gonna use the System.Data.SqlClient namespace.
SqlConnection myConnection = new SqlConnection("your connection string");
myConnection.Open();
string id = "my_id";
string text;
string fileName;
SqlCommand query = new SqlCommand();
query.CommandText = "SELECT FileName, SubtitleText FROM Subtitles WHERE ID = '#id'";
query.Parameters.AddWithValue("#id", id);
query.Connection = myConnection;
SqlDataReader data = query.ExecuteReader();
while (data.Read()) {
text = (string)data["SubtitleText"];
fileName = (string)data["FileName"];
}
using (FileStream fs = File.Create(file + ".srt")) {
File.WriteAllText(file, text);
}
This is kind of bad code but it roughly gives the idea of what you can do to achieve your goal (As i understood it*). If the ID is int, you can change it to that.
Addendum: English is not my first language so excuse the mistakes.

Categories