How to create a file in WCF service application in windows - c#

I'm working on WCF services application. I want to create a file in one of my function
so now this time I'm doing like this. First I go to directory creates a file then i do read/write.
string path = AppDomain.CurrentDomain.BaseDirectory;
path += "Emp_data\\json_data.json";
StreamReader reader = new StreamReader(path);
StreamWriter writer = new StreamWriter(path);
I know I'm doing this in wrong way. Please suggest me a better way so that if there in no file and folder It will create automatically.

Nothing extra happens with creating a file in WCF so you can do that like this
string path = AppDomain.CurrentDomain.BaseDirectory;
String dir = Path.GetDirectoryName(path);
dir += "\\Emp_data";
string filename = dir+"\\Json_data.json";
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir); // inside the if statement
FileStream fs = File.Open(filename,FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader reader = new StreamReader(fs);

Creating a file has nothing to do with WCF. Doing so is the same regardless of the context. I prefer to use the methods on the static File class.
To create a file is simple.
string path = AppDomain.CurrentDomain.BaseDirectory;
path += "Emp_data\\json_data.json";
using(FileStream fs = System.IO.File.Create(path))
{
}
If you just want to write data, you can do...
File.WriteAllText(path, contentsIWantToWrite);

Your problem is not related to WCF services in general.
Something like this will work (if you have write access to the file):
String dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir)
using (FileStream fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
// work with fs to read from and/or write to file, maybe this
using (StreamReader reader = new StreamReader(fs))
{
using (StreamWriter writer = new StreamWriter(fs))
{
// need to sync read and write somehow
}
}
}

Related

Is it ok to handle text file by Streamreader & StreamWriter without prior use of FileStream?

Is it still good practise to handle the text file withot using FileStream like in an example below:
StreamWriter sw2 = new StreamWriter(filePath);
sw2.WriteLine("Some text");
sw2.Close();
StreamReader sr2= new StreamReader(filePath);
string text =sr2.ReadToEnd();
Console.WriteLine(text);
sr2.Close();
Or it is much better to use FileStream class first:
string filePath= #"C:\Users\Dom\OneDrive\CODE\Temp29-01-2021\TextFile1.txt";
FileStream fs = new FileStream(filePath,FileMode.Create);
StreamWriter sw= new StreamWriter(fs);
foreach (var item in list)
sw.WriteLine("Some text");
sw.Close();
fs =new FileStream(filePath, FileMode.Open);
string line;
StreamReader sr = new StreamReader(fs);
while ((line=sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
sr.Close();
Is it better to use it with FileStream, if so why?
Is it better to use with FileStram for asynchronous operations?
And the last question is : if we use FileStream class for writing and reading from hte same file,
do we have to always create two seperate instances of FileStream - one for writing and another for reading from specified text file?

Storing more than one value into Isolated Storage

I have created a isolated storage that only store one values and display one value of e.g. "aaaaaaaa,aaaaaaaa".
How can I make it so that it stores
1)"aaaaaaaa,aaaaaaaaa"
2)"bbbbbbbb,bbbbbbbbb"
3)"cccccccccc,cccccccccc"
Below shows codes that stores only one value:
//get the storage for your app
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
//define a StreamWriter
StreamWriter writeFile;
if (!store.DirectoryExists("SaveFolder"))
{
//Create a directory folder
store.CreateDirectory("SaveFolder");
//Create a new file and use a StreamWriter to the store a new file in
//the directory we just created
writeFile = new StreamWriter(new IsolatedStorageFileStream(
"SaveFolder\\SavedFile.txt",
FileMode.CreateNew,
store));
}
else
{
//Create a new file and use a StreamWriter to the store a new file in
//the directory we just created
writeFile = new StreamWriter(new IsolatedStorageFileStream(
"SaveFolder\\SavedFile.txt",
FileMode.Append,
store));
}
StringWriter str = new StringWriter();
str.Write(textBox1.Text);
str.Write(",");
str.Write(textBox2.Text);
writeFile.WriteLine(str.ToString());
writeFile.Close();
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
StringWriter str = new StringWriter();
str.Write(textBox1.Text);
str.Write(",");
str.Write(textBox2.Text);
writeFile.WriteLine(str.ToString());
writeFile.Close();
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
You can use WriteLine several times like below
writeFile.WriteLine(string.Format("{0},{1}", "aaaaa","aaaaa"));
writeFile.WriteLine(string.Format("{0},{1}", "bbbbb","bbbbb"));
writeFile.WriteLine(string.Format("{0},{1}", "ccccc","ccccc"));
I can confirm Damith's answer, and should be marked as so.
If you're wondering about reading the lines back in:
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("SaveFolder", FileMode.Open, store);
StreamReader reader = new StreamReader(stream);
string rdr = reader.ReadLine();
rdr will be a string representing the first line, you can then call ReadLine() again to get the next line, etc. The first call to ReadLine() will return the first line you wrote to the store.
Hope this is useful to you or anyone else working in this area.

encrypting a copy of a text file in c# (Windows Forms)

I'm working on an encryption program in C# (Windows Forms) and one of the options I'd like to add is that the user will be able to choose an existing text (.txt) file, and the program would make a new file which is the file chosen, but encrypted (without making any changes in the original file).
I though about making a copy of the original file and then encrypting the new file, but I have no clue how to do it.
Please tell me how to do it.
Thanks a lot in advance!
StreamReader/StreamWriter for loading and saving the file.
StreamReader:
string unencryptedText;
private void ReadTextFile()
{
using (StreamReader reader = new StreamReader("file.txt"))
{
unencryptedText= reader.ReadToEnd();
}
}
StreamWriter
using (StreamWriter writer = new StreamWriter("encryptedFile.txt", true))
{
writer.Write(encryptedText);
}
Encryption: Simple insecure two-way "obfuscation" for C#
Update
Chose Directory where to save encrypted file(only Directory)
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(fbd.SelectedPath+"\\encryptedFile.txt", true))
{
writer.Write(encryptedText);
}
}
Chose Directory and FileName
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(sfd.FileName, true))
{
writer.Write(encryptedText);
}
}
Use System.IO.StreamReader and System.IO.StreamWriter to read and write from text files.
http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
using (StreamReader sr = new StreamReader(filePath))
{
fileContents = sr.ReadToEnd();
}
string encryptedContents = Encrypt(fileContents);
using (StreamWriter sw = new StreamWriter(destinationPath))
{
sw.Write(encryptedContents);
}
File.Copy(pathX,pathY)
Will copy the file from path X to path Y.
The next thing is to write the encrypted text to the copied file:
File.WriteAllText(pathY,textToWrite)
I can also say you will learn more if you read msdn examples.
Everything you look for is there.

IsolatedStorage in Window Phone 7.5

I am working with IsolatedStorage in Windows Phone 7.5. I am trying to read some text from a file. But the debugger says the operation is not permitted on IsolatedStorageFileStream. Why?
//Read the file from the specified location.
fileReader = new StreamReader(new IsolatedStorageFileStream("info.dat", FileMode.Open, fileStorage));
//Read the contents of the file (the only line we created).
string textFile = fileReader.ReadLine();
//Write the contents of the file to the MEssageBlock on the page.
MessageBox.Show(textFile);
fileReader.Close();
UPD my new code
object _syncObject = new object();
lock (_syncObject)
{
using (var fileStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (FileStream stream = new FileStream("/info.dat", FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new StreamReader(stream))
{
string textFile = reader.ReadLine();
MessageBox.Show(textFile);
}
}
}
}
}
Try this, it works for me: Hope it works for you too
String sb;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(fileName))
{
StreamReader reader = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, myIsolatedStorage));
sb = reader.ReadToEnd();
reader.Close();
}
if(!String.IsNullOrEmpty(sb))
{
MessageBox.Show(sb);
}
}
If this doesn't work, then maybe your file doesn't exist.
Normally when I've used isolated storage, I've done something like:
using (var stream = fileStorage.OpenFile("info.dat", FileMode.Open))
{
using (var reader = new StreamReader(stream))
{
...
}
}
... rather than calling the constructor directly on IsolatedStorageFileStream. I can't say for sure whether that'll sort it out, but it's worth a try...
Just a guess:
WP emulator will reset all Isolatd Storage contents when it's closed
if you used FileMode.Open with a path to a non existing file you'll get Operation not permited exception.
You can use fileStorage.FileExists() to check if the file is there or use FileMode.OpenOrCreate.

How to open a text file in read-only mode means there i can not perform write?

I am trying it too much time but can not achieve the goal. File is opened but its opened in write mode.
Code-
in txtpath.text, I am passing the path of the text:
System.IO.FileInfo fileObj= new System.IO.FileInfo(txtPath.Text);
fileObj.Attributes = System.IO.FileAttributes.ReadOnly;
System.Diagnostics.Process.Start(fileObj.FullName);
use the File.OpenRead method
string sFilename = "myfile.txt";
FileStream SR = File.OpenRead(sFilename);
Opening a file to only read it's contents:
// Open the stream and read it back.
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
More about File.OpenRead: http://msdn.microsoft.com/en-us/library/system.io.file.openread.aspx
Setting a file's ReadOnly attribute and executing it:
File.SetAttributes(txtPath.Text, File.GetAttributes(txtPath.Text) | FileAttributes.ReadOnly);
System.Diagnostics.Process.Start(txtPath.Text);

Categories