problems with Create a path from a few strings in c# - c#

I got a little problem. In the following code i recieve a file and the ending of the file from Networkstream. After that the File is saved under the path i received. Everytime i run the code i get the path.getinvalidpathchars exception. here is a short code example:
ns.Read(ending,0,1212);
string endung = "saved." + Encoding.UTF8.GetString(ending);
string path = Path.Combine(#"c:\users\user\desktop\" , endung);
Console.WriteLine(path);
File.WriteAllBytes(path ,file);
the byte array file is an array of bytes from the file i received. the full path is c:\users\user\desktop\saved. and the rest (txt, jpg, exe) should be changebel (that means if the received string sas "txt" the path should be c:\users\user\desktop\saved.txt if it sas "exe" c:\users\user\desktop\saved.exe and so on)!

I solved the problem with a StreamReader!
//byte[] file = File.ReadAllBytes(#"c:\users\user\desktop\file.txt");
TcpListener listen = new TcpListener(IPAddress.Parse(mes),223);
listen.Start();
TcpClient client = listen.AcceptTcpClient();
NetworkStream ns = client.GetStream();
StreamReader sre = new StreamReader(ns);
string ende = sre.ReadLine();
string path = Path.Combine(#"c:\users\user\desktop\file2." + ende);
Console.WriteLine(path);
File.WriteAllBytes(path ,file);
listen.Stop();

Related

Streamed File Contains Strange Characters - An Encoding Issue

I have a WCF service end-point which generates an excel file and returns this file as a MemoryStream in the end in order to make client download the relevant file.
The file generated on the respective directory has no issues. I don't see any strange characters when I open and check it.
But, the file I returned with MemoryStream is full of strange unreadable characters.
My end-point is like that,
public Stream GetEngagementFeedFinalizeData(int workspaceId, string startDate, string endDate, Stream data)
{
try
{
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;";
string extension = "xls";
string fileName = "report-" + DateTime.Now.Ticks.ToString();
string contentDisposition = string.Format(CultureInfo.InvariantCulture, "attachment; filename={0}.{1}", fileName, extension);
WebOperationContext.Current.OutgoingResponse.ContentType = contentType;
WebOperationContext.Current.OutgoingResponse.Headers.Set("Content-Disposition", contentDisposition);
//Here is some business logic and fetching data from db. Not any encoding
//related issue. The data set is assigned to a variable
//named "feedFinalizeDataTable" in the end
feedFinalizeDataTable.TableName = "Summary";
DataSet dataSet = new DataSet();
dataSet.Tables.Add(feedFinalizeDataTable);
using (ExcelPackage excelPackage = new ExcelPackage())
{
foreach (DataTable dt in dataSet.Tables)
{
ExcelWorksheet sheet = excelPackage.Workbook.Worksheets.Add(dt.TableName);
sheet.Cells["A1"].LoadFromDataTable(dt, true);
}
var path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory);
var filePath = path + "\\" + "New.xls";
excelPackage.SaveAs(new System.IO.FileInfo(filePath)); //This file is flawless
FileStream fs = new FileStream(filePath, FileMode.Open);
int length = (int)fs.Length;
WebOperationContext.Current.OutgoingResponse.ContentLength = length;
byte[] buffer = new byte[length];
int sum = 0;
int count;
while ((count = fs.Read(buffer, sum, length - sum)) > 0)
{
sum += count;
}
fs.Close();
return new MemoryStream(buffer); //This file is full of unreadable chars as per above shared screenshot
}
I'm using OfficeOpenXml to generate excel files.
Then, I checked both files encoding by open them with notepad. I saw that the file on the directory (the flawless one) has ANSI encoding. And, the one which is returned by the end-point (the broken one) has UTF-8 encoding.
After that, I try to change the encoding type of the stream like this,
var byteArray = System.IO.File.ReadAllBytes(filePath);
string fileStr = new StreamReader(new MemoryStream(byteArray), true).ReadToEnd();
var encd = Encoding.GetEncoding(1252); //On the other topics I saw that ANSI represented with 1252
var end = encd.GetBytes(fileStr);
return new MemoryStream(end);
But, this doesn't help too. Though some of the strange characters are replaced with some other strange characters, but as I said, streamed file is still unreadable. And, when I open it with notepad to see its encoding, I saw that its still UTF-8.
Thus, I'm kind of stuck. I have also try directly to stream the generated excel file (without writing it to a directory and then reading it) with OfficeOpenXml's built in function called .GetAsByteArray(), but the downloaded file looks exactly the same as per above screenshot.
Thanks in advance.

C# error on reading mp3 file by binary reader : The process cannot access the file 'URL\testbinary.mp3' because it is being used by another process

hiiii,
i want to read mp3 file by using binary reader, my code is :
using (BinaryReader br = new BinaryReader(File.Open("Songs/testbinary.mp3", FileMode.Open)))
{
int length = (int)br.BaseStream.Length;
byte[] bytes = br.ReadBytes(length);
txtBinary.Text = bytes.ToString();
}
.......
when i execute this code it shows and exception:
The process cannot access the file 'URL\testbinary.mp3' because it is being used by another process.
where "URL" is my actual file location.
You open the same file twice (without any sharing option). To read the content of a file as bytes you can use File.ReadAllBytes
byte[] bytes = File.ReadAllBytes("Songs/testbinary.mp3");
BTW: Don't forget txtBinary.Text = bytes.ToString(); doesn't give you what you think. You will have to use BitConverter.ToString or Convert.ToBase64String

PDF Upload error System.IO.DirectoryNotFoundException: Could not find a part of the path

I have developed an ASP.net C# function to upload PDF to the Database. when I try it in LocalHost, its working perfectly fine. but when I publish it in a server on IIS. it gives me the below error when I click upload:
System.IO.DirectoryNotFoundException: Could not find a part of the
path + <path of the file>
string filePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
Is there anything I should change in order to be able to upload?
When you access it from localhost, both client and server are same so it can find file. but when you publish both the machine are isolated. basically you are not getting content from uploaded file, what you did is get the filename and fetch data from local hard disk, you should use following snippet.
int fileLen = fu.PostedFile.ContentLength;
Byte[] Input = new Byte[fileLen];
Stream myStream = fu.PostedFile.InputStream;
myStream.Read(Input, 0, Input.Length);
I have declared an byte array with size of bytes in uploaded file. and read byte from PostedFile InputStream.

process cannot access the image file because it is being used by another process

i downloaded images from my deployed website and save it into my WPF app folder , basically i am running 2 platforms , a website and WPF . What i am trying to do is users uploaded their images using the web , so on the WPF side , i download the image from the web and display on my WPF app but i got this error :
The process cannot access the file
'C:\Users\apr13mpsipa\Desktop\OneOrganizer\OneOrganizer\bin\Debug\TaskImage\Fill
in the blanks.jpg' because it is being used by another process.
This is the code :
protected void DownloadData(string strFileUrlToDownload, string taskName)
{
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
MemoryStream storeStream = new MemoryStream();
storeStream.SetLength(myDataBuffer.Length);
storeStream.Write(myDataBuffer, 0, (int)storeStream.Length);
storeStream.Flush();
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
using (FileStream file = new FileStream(currentpath, FileMode.Create, System.IO.FileAccess.ReadWrite)) // ERROR HERE
{
byte[] bytes = new byte[storeStream.Length];
storeStream.Read(bytes, 0, (int)storeStream.Length);
file.Write(myDataBuffer, 0, (int)storeStream.Length);
storeStream.Close();
}
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
}
I got the error when i try to display a image on a first button click , then i display the image again on the other button . basically this happens when i try to display the image 2 times.
---EDIT ------
Updated as of baldrick's comment :
DownloadData(fileUploadDirectory + daoTask.GetImage(aid, actTask.taskID).Substring(1), daoTask.GetTaskName(aid, actTask.taskID));
Image imgActivityTask = new Image();
imgActivityTask.Height = 90;
imgActivityTask.Width = 90;
imgActivityTask.Margin = new Thickness(10);
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(currentpath, UriKind.Absolute);
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.EndInit();
imgActivityTask.Source = img;
Its still giving me the same error on the using line.
In you WPF code, you might need to specify the IgnoreImageCache setting:
yourImage.CacheOption = BitmapCacheOption.OnLoad;
yourImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache
This might force it to load, and not lock the file.
The answer here deals with the same problem.
I am guessing you are leaving the file stream open.
Not sure why you are creating a memory stream (by the way, don't forget to close memory stream), and a file stream when you already have the bytes? Why not directly write to the file using File.WriteAllBytes?
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
File.WriteAllBytes(currentPath, myDataBuffer);
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
Not sure why you are creating a memory stream (by the way, don't forget to close memory stream), and a file stream when you already have the bytes? Why not directly write to the file using File.WriteAllBytes?
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
File.WriteAllBytes(currentPath, myDataBuffer);
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
Thanks

Save a file on a ftp server in a subdirectory

I have code that allows me to access a server to do ftp transactions. I have tested the connection and it works. the problem is saving files. to help paint a picture this is how the address are set up.
ftp server: ftp.MyMainDomain.com
path login ftp points to: www.another_website_Under_myDomain.com/gallery/images
when I tested connection, ftp server tacks me directly to images folder and I have even read the subdirectories out (ie ..images/subdirectory1, ..images/subdirectory2).
What I need now it to be able to save files into each of the folders. I thought that all I had to do was add subdir that I wanted to access to the end of the ftp_server uri but that doesn't work. What should I do?
Uri ftpUri = new Uri((Ftp_Server_Address + "/" + SubDirectory+ "/"), UriKind.Absolute);
if (ftpUri.Scheme == Uri.UriSchemeFtp)// check ftp address,
{
DirRequest = (FtpWebRequest)FtpWebRequest.Create(ftpUri);
DirRequest.Method = ReqMethod;
DirRequest.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
DirRequest.UsePassive = true;
DirRequest.UseBinary = true;
DirRequest.KeepAlive = false;
//change picture to stream
Stream PicAsStream = Pic.Bitmap_to_Stream(Pic.BitmapImage_to_Bitmap(Pic.Photo));
//send ftp with picture
Stream ftpReqStream = DirRequest.GetRequestStream();
ftpReqStream = PicAsStream;
ftpReqStream.Close();
SendFtpRequest(ReqMethod);
}
In this line:
ftpReqStream = PicAsStream;
You are not sending the Stream to ftp Server but you are assigning PicAsStream to ftpReqStream and then closing it. Your code does nothing.
Do it like this:
Create a buffer of your image file (not a stream):
FileStream ImageFileStream = File.OpenRead(your_file_path_Here);
byte[] ImageBuffer = new byte[ImageFileStream.Length];
ImageFileStream.Read(ImageBuffer, 0, ImageBuffer.Length);
ImageFileStream.Close();
and then simply write it to your ftpReqStream:
Stream ftpReqStream = DirRequest.GetRequestStream();
ftpReqStream.Write(ImageBuffer, 0, ImageBuffer.Length);
ftpReqStream.Close();

Categories