How I can display Stream on the page? - c#

I have a WCF method that I am calling, the method suppose to create a file but it create an exception. I try to find what is in the stream request that I am passing to this method. How I can alert or write this stream so I can find the content. That is my method:
Stream UploadImage(Stream request)
{
Stream requestTest = request;
HttpMultipartParser parser = new HttpMultipartParser(request, "data");
string filePath = "";
string passed = "";
if (parser.Success)
{
// Save the file somewhere
//File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
// Save the file
//SaveFile( mtp.Filename, mtp.ContentType, mtp.FileContents);
FileStream fileStream = null;
BinaryWriter writer = null;
try
{
filePath = HttpContext.Current.Server.MapPath("Uploded\\test.jpg"); // BuildFilePath(strFileName, true);
filePath = filePath.Replace("SSGTrnService\\", "");
fileStream = new FileStream(filePath, FileMode.Create);
it produces an error on this line :
fileStream = new FileStream(filePath, FileMode.Create);
that I try to understand why file can not created.

Given the information you gave, I can only assume that your code tries to create the file test.jpg somewhere where your application is not allowed to write. A common mistake would be somewhere in the Program files folder. In modern Windows versions, that is specially protected.

Related

I'm getting "The process cannot access the file because it is being used by another process" error. Any ideas?

So, I created a file and a txt file into the AppData, and I want to overwrite the txt. But when I try to do it, it keeps giving me that error. Any ideas?
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string setuppath = (path + "\\");
string nsetuppath = (setuppath + "newx" + "\\");
Directory.CreateDirectory(nsetuppath);
string hedef2 = (nsetuppath + "commands.txt");
File.Create(hedef2);
StreamWriter sw = new StreamWriter(hedef2); ----> This is where the error appears.
sw.WriteLine("Testtest");
Just use the using statement when using streams. The using statement automatically calls Dispose on the object when the code that is using it has completed.
//path to the file you want to create
string path = #"C:\code\Test.txt";
// Create the file, or overwrite if the file exists.
using (FileStream fs = File.Create(path))
{
byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
There are many ways of manipulate streams, keep it simple depending on your needs

Unable to scan Outlook Attachment for encryption

I am trying to detect an encrypted attachment using ICSharpCode.SharpZipLib,
but the code breaks while debugging on this line:
FileStream fileStreamIn = new FileStream(attachtype, FileMode.Open, FileAccess.Read);
Is there any other way through which I can get Outlook attachment and scan for encryption?
if (attachments.Count != 0)
{
for (int i = 1; i <= mail.Attachments.Count; i++)
{
String attachtype = mail.Attachments[i].FileName.ToLower();
if (extensionsArray.Any(attachtype.Contains))
{
FileStream fileStreamIn = new FileStream(attachtype, FileMode.Open, FileAccess.Read);
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
ZipEntry entry = zipInStream.GetNextEntry();
MessageBox.Show("IsCrypted: " + entry.IsCrypted);
}
}
}
I'm assuming you are using Microsoft.Office.Interop.Outlook namespaces.
According to the MSDN the Filename property does the following (source):
Returns a String (string in C#) representing the file name of the
attachment. Read-only.
So the value is only the name of the file, not the location (it does not exist on disk as a accessible file). When supplying just the filaneme into a FileStream it will attempt to open a file with that name in the local directory (which probably does not exist).
It seems from the documentation you'll need to store it using the SaveAsFile method (source) into a temporary file and load a FileStream from that.
So something like:
// Location to store file so we can access the data.
var tempFile = Path.GetTempFileName();
try {
// Save attachment into our file
mail.Attachments[i].SaveToFile(tempFile);
using(var stream = File.OpenRead(tempFile)) {
// Do stuff
}
} finally {
// Cleanup the temp file
File.Delete(tempFile);
}

Xamarin android data saving to json file

I need to save the file when method OnDestroy is called and load same file when method OnCreate is called. At this time I can read json file easily from Assets (this works fine)
StreamReader reader = new StreamReader(Assets.Open("reiksmes.json"));
string JSONstring = reader.ReadToEnd();
Daiktai myList = JsonConvert.DeserializeObject<Daiktai>(JSONstring);
items.Add(myList);
, but I have some problems when I try to save(write) Daiktai class data to the same file I opened above. I tried:
string data = JsonConvert.SerializeObject(items);
File.WriteAllText("Assets\\reiksmes.json", data);
with this try I get error System.UnauthorizedAccessException: Access to the path "/Assets
eiksmes.json" is denied.
also tried:
string data = JsonConvert.SerializeObject(items);
StreamWriter writer = new StreamWriter(Assets.Open("reiksmes.json"));
writer.WriteLine(data);
and with this try I get error System.ArgumentException: Stream was not writable.
Summary:
I think I chose bad directory(Assets), I need to save and load data (json format). So where do I need to save them and how(give example)?
You can't save anything to assets. You can just read from it. You have to save the file to a different folder.
var fileName = "reiksmes.json";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, fileName);
Console.WriteLine(path);
if (!File.Exists(path))
{
var s = AssetManager.Open(fileName);
// create a write stream
FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
// write to the stream
ReadWriteStream(s, writeStream);
}

Creating the same bin file as content of string C#

I would like to create a bin file for example file.bin with the same content as a string variable contains. For example I have string str="10101" and I want to create conversion of str's content to bin file. After conversion, when I open file.bin I want to see the same content as str: 10101. I tried to do that by this way:
string path = "files/file.bin";
string str = "10101";
File.Create(path);
BinaryWriter bwStream = new BinaryWriter(new FileStream(path, FileMode.Create));
BinaryWriter binWriter = new BinaryWriter(File.Open(path, FileMode.Create));
for (int i = 0; i < str.Length; i++)
{
binWriter.Write(str[i]);
}
binWriter.Close();
but i get exception like
"System.IO.IOException: The process can not access the file
"C:\path.."
because it is being used by another process.. and few more exception.
The path/file you are trying to access is used by some other application. Close all the application which can/has opened the file,file.bin, which you are creating and then the code. It should work. You can remove bwStream variable line, if no other application is running.
You get the error because you are opening the file twice. The second time fails because the file is already open.
To write the string to the file you can just use the File.WriteAllText method:
string path = "files/file.bin";
string str = "10101";
File.WriteAllText(path, str);
Note: The string is encoded as utf-8 when it is written to the file.
File.Create() uses the file, try:
File.Create(path).Dispose();
BinaryWriter bwStream = new BinaryWriter(File.Open(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));

USING FileStream and handling its weird exceptions

The following code works for me when i have a fixed file+filepath declared in my code and is understood to work.
NetworkStream netStream = client.GetStream();
string FileName = #"D:\John\FYL\video1.mp4";
Directory.CreateDirectory(Path.GetDirectoryName(FileName));
using (FileStream fs = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write))
{
netStream.CopyTo(fs);
}
netStream.Close();
}
But fails for this protion.
NetworkStream netStream = client.GetStream();
// FileName is taken at run time on button click from textbox.
using (FileStream fs = new FileStream(#"D:\John\FYL\"+FileName, FileMode.OpenOrCreate, FileAccess.Write))
{
netStream.CopyTo(fs);
}
netStream.Close();
}
Now when i checked another case, using File.Create and getting FileName at run-time it works.
FileStream output = File.Create(#"D:\John\" + FileName)
I'm in doubt because i have to get the saving location at run-time from Browse dialog but why FileStream fs = new FileStream(#"D:\John\FYL\+FileName throws exceptions like System.IO.DirectoryNotFoundException and System.UnauthorizedAcessException although i changed security settings for my local drives.
Does thread affecting all this as this code is a part of code loaded at run-time and browse is a click event ?
You need to ensure that the directory exists before trying to create the file.
NetworkStream netStream = client.GetStream();
if (!Directory.Exists(#"D:\John\FYL\" + FileName)) {
Directory.CreateDirectory(#"D:\John\FYL\" + FileName);
}
using (FileStream fs = new
FileStream(#"D:\John\FYL\" + FileName, FileMode.OpenOrCreate, FileAccess.Write))
{
netStream.CopyTo(fs);
}
netStream.Close();
You may also want to check that the variable FileName is properly formatted. Since you are already providing a trailing backslash "D:\John\FYL\", check that FileName is not \File1.mp4, which will concatenate into "D:\John\FYL\\File1.mp4", which is incorrect.
have you tried looking at the value of FileName? probably it's giving wrong value.
If File name contains only the name of the file, then be sure to give the name along with file extension, if there isn't any extension provided, your program will treat the name as a directory extension which it is not able to find.
If the File name contains the name along with directory heirarchy then you are simply concatenating one directory to your "D:\John\" directory which again is wrong.

Categories

Resources