I have created a TCP server in c# which receives a file from a client and keeps it in the current directory. The code segment which does this is as follows:
using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))
{
fStream.Write(buffer, 0, buffer.Length);
fStream.Flush();
fStream.Close();
}
Console.WriteLine("File received and saved in " + Environment.CurrentDirectory);
where cmdFileName is the received filename.
Now I have created a folder named "test" inside the current directory using the following code:
string root = Environment.CurrentDirectory;
string folder = Path.Combine(root,"test");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
I want to keep the received file inside the "test" folder. I need to make change to the following line of my previous code segment:
using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))
But what change will I have to make?
You are using Path.Combine to get the path of the new test directory--you just need to use it again to find the path of the cmdFileName file inside the test directory:
string cmdFilePath = Path.Combine(folder, Path.GetFileName(cmdFileName));
using (FileStream fStream = new FileStream(cmdFilePath, FileMode.Create))
After this code:
string root = Environment.CurrentDirectory;
string folder = Path.Combine(root,"test");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
Add another usage of the Path.Combine since you want to attach the path folder to the file cmdFileName:
string fullFilePath = Path.Combine(folder, Path.GetFileName(cmdFileName));
using (FileStream fStream = new FileStream(fullFilePath, FileMode.Create))
{
...
}
Console.WriteLine("File received and saved in " + fullFilePath);
Also you should want to do it inside a try block in order to announce that it succeeded only if it really did:
try
{
using (FileStream fStream = new FileStream(fullFilePath, FileMode.Create)) //Exception accessing the file will prevent the console writing.
{
...
}
Console.WriteLine("File received and saved in " + fullFilePath);
}
catch (...){...Console.WriteLine("Could not write to file " + fullFilePath);...}
Related
This question already has an answer here:
File.Delete the process cannot access the file because it is being used by another process
(1 answer)
Closed 2 years ago.
I need to create small console application to move files into separate folders. Everything works fine, I can copy file, until I try to File.Move or File.Delete file, I catch System.UnauthorizedAccessException. What I've tried
changing folder permission from code
switching from .Net Core to .Net Framework
Manually adding permission to folder by rightclicking->Security->Advance
tried to change Folder's Read-only attribute (it always reverts back to readonly, I can't solve this)
I don't know what else I can try and how to solve this problem. The code I wrote is below
var pngFiles = Directory.GetFiles(#"C:\Users\MSI_PC\Desktop\Test", "*.png",
SearchOption.AllDirectories);
foreach (var pngFile in pngFiles)
{
Console.WriteLine(pngFile);
var fileName = Path.GetFileName(pngFile);
var newFolder = Path.Combine(#"C:\Users\MSI_PC\Desktop\Test",
Path.GetFileNameWithoutExtension(fileName));
Directory.CreateDirectory(newFolder);
var newFileName = Path.Combine(#"C:\Users\MSI_PC\Desktop\Test",
Path.GetFileNameWithoutExtension(fileName), fileName);
File.Copy(pngFile, newFileName, true); //yes, I can use move and have 1 line of code instead of 2. But I need file to be copied, and this line of code works fine
File.Delete(pngFile); // System.UnauthorizedAccessException. File.Move throws the same exception
}
try this code
private void Copy()
{
var pngFiles = Directory.GetFiles(#"C:\Users\Administrator\Desktop", "*.png", SearchOption.AllDirectories);
foreach (var pngFile in pngFiles)
{
Console.WriteLine(pngFile);
var fileName = Path.GetFileName(pngFile);
var newFolder = Path.Combine(#"D:\NewPic\");
Directory.CreateDirectory(newFolder);
string DestPath = newFolder + "\\" + fileName;
byte[] buffer = new byte[2014 * 1024];
using (FileStream source = new FileStream(pngFile, FileMode.Open, FileAccess.Read, FileShare.Delete))
{
using (FileStream dest = new FileStream(DestPath, FileMode.CreateNew, FileAccess.Write, FileShare.Delete))
{
int currentBlockSize = 0;
while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, currentBlockSize);
}
dest.Close();
}
source.Close();
}
File.Delete(pngFile); // System.UnauthorizedAccessException. File.Move throws the same exception
}
}
I am developing an application which store filename in database. For Mozilla & Chrome it is showing FileName only but in IE it is showing full path of file. Now I want to check whether given filename is filename or filepath. Is there any way to do it?
Here is my code:
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
byte[] image = null;
var file = attachments.First();
// Some browsers send file names with full path. We only care about the file name.
string filePath = Server.MapPath(General.FaxFolder + "/" + file.FileName);
file.SaveAs(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using (BinaryReader br = new BinaryReader(fs))
{
image = br.ReadBytes((int)fs.Length);
}
TempData["Image"] = image;
System.IO.File.Delete(filePath);
return Json(new { status = "OK", imageString = Convert.ToBase64String(image) }, "text/plain");
}
Well,If you go with getting filename only in any browser then you should write
Path.GetFileName(e.fileName);
It will return filename only in any browser
Thanks
Instead of check whether the file has a path or not, what you can do is to just use
GetFileName(path);method
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
}
}
}
1) I am having a problem in reading a text file from my given path .
2) When i download the zip file from ftp i extracted it my extracting is working fine ,
3) The problem is when i download the file from ftp the file which i download is zip file i extract it to a text file and delete the zip file after extracting it and when i
try to read text file from the given path, the path reads the zip file not a text file
4) the code i am using for FTP and extracting the zipfile is,
private void DownloadMonth(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + ftpMonth + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = true;
reqFTP.UsePassive = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long c1 = response.ContentLength;
int bufferSize = 2048000;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
string Path1 = (string)(Application.StartupPath + "\\TEMP\\TEMP_BACKFILL_" + "\\" + fileName);
DirectoryInfo di = new DirectoryInfo(Path1);
FileInfo fi = new FileInfo(Path1);
Decompress(fi);
File.Delete(Path1);
}
catch (Exception ex)
{
}
}
Decompress Code
public static void Decompress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Get original file extension, for example "doc" from report.doc.gz.
string curFile = fi.FullName;
string origName = curFile.Remove(curFile.Length - fi.Extension.Length);
//Create the decompressed file.
//using (FileStream outFile = File.Create(fi.FullName + ""))
//using (FileStream outFile = File.Create(System.Text.RegularExpressions.Regex.Replace(fi.FullName, ".txt$", "") + ""))
using (FileStream outFile = File.Create(origName + ".txt"))
{
using (GZipStream Decompress = new GZipStream(inFile,
CompressionMode.Decompress))
{
//Copy the decompression stream into the output file.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = Decompress.Read(buffer, 0, buffer.Length)) != 0)
{
outFile.Write(buffer, 0, numRead);
}
Console.WriteLine("Decompressed: {0}", fi.Name);
}
}
}
}
The code i use to download the text file from FTP and read the text file is
private void button1_Click(object sender, EventArgs e)
{
this.DownloadMonth(a, name_Month);
string Path1 = (string)(Application.StartupPath + "\\TEMP\\TEMP_BACKFILL_" + "\\" + name_Month);
StreamReader reader1 = File.OpenText(Path1);
string str = reader1.ReadToEnd();
reader1.Close();
reader1.Dispose();
}
There would be a great appreciation if someone can solve my problem.
Thanks In Advance
It looks like you're trying to read the binary file from your button1_Click method, instead of the text file. That's just a matter of giving it the wrong filename. You could try just using:
string Path1 = Application.StartupPath + "\\TEMP\\TEMP_BACKFILL_\\"
+ name_Month + ".txt";
(in button1_Click)
... but really you should be able to diagnose what's going wrong yourself:
Is the file being downloaded correctly?
Is the decompression working?
Does the text file look okay afterwards (on the file system)?
If everything's working up to that point, then the download and decompression code is irrelevant, and it's obviously just the reading part in the click handler which is failing. If the text file isn't being created properly, then obviously something is wrong earlier in the process.
It's important to be able to diagnose this sort of thing yourself - you've got a clear 3-step process, and the results of that process should be easy to find just by looking on the file system, so the first thing to do is work out which bit is failing, and only look closely at that.
As an aside, in various places you're manually calling Close on things like streams and readers. Don't do that - use a using statement instead. You should also look at File.ReadAllText as a simpler alternative for reading the whole of a text file.
try string Path1 = origName + ".txt" in button click
I am having two problems
My problems are
My file name is 20110505.txt , and it is compressing a zip file name as -> 20110505.txt.zip
But I need after compressing this file 20110505.txt as --> 20110505.zip only.
I am using this dll
using System.IO.Compression;
Here is my code for compress,
1)is my text format
string path = DayDestination + "\\" + txtSelectedDate.Text + ".txt";
StreamWriter Strwriter = new StreamWriter(path);
DirectoryInfo di = new DirectoryInfo(path);
FileInfo fi = new FileInfo(path);
Compress(fi);
public static void Compress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Prevent compressing hidden and already compressed files.
if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
!= FileAttributes.Hidden & fi.Name != ".zip")
{
// Create the compressed file.
using (FileStream outFile = File.Create(fi.FullName + ".zip"))
//using (FileStream outFile = File.Create( fi.Name+ ".zip"))
{
using (GZipStream Compress = new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into the compression stream.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
{
Compress.Write(buffer, 0, numRead);
}
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
}
If my zip file name is 20110505.zip after uncompressing i want my file name to be 20110505.txt . after uncomressing the zip file to text file i want to delete the zip file after compressing
string Path2 = (string)(Application.StartupPath + "\\TEMP\\" + "\\" + name_atoz);
DirectoryInfo di = new DirectoryInfo(Path2);
FileInfo fi = new FileInfo(Path2);
Compress(fi);
public static void Decompress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Get original file extension, for example "doc" from report.doc.gz.
string curFile = fi.FullName;
string origName = curFile.Remove(curFile.Length - fi.Extension.Length);
//Create the decompressed file.
using (FileStream outFile = File.Create(origName))
{
using (GZipStream Decompress = new GZipStream(inFile,
CompressionMode.Decompress))
{
//Copy the decompression stream into the output file.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = Decompress.Read(buffer, 0, buffer.Length)) != 0)
{
outFile.Write(buffer, 0, numRead);
}
Console.WriteLine("Decompressed: {0}", fi.Name);
}
}
}
}
I want this because i am creating a project which reads the text file .
Is there any suggestion for my problem.
Thanks In Advance
As Mitch pointed out in the comments above, the problem seems to be with your file name being used for the zip file. You include the FullName, but that has the .txt at the end. Trim that off and you should have what you want.
The line I'm talking about is this one:
using (FileStream outFile = File.Create(fi.FullName + ".zip"))
A simple way to fix it would be as follows:
using (FileStream outFile = File.Create(System.Text.RegularExpressions.Regex.Replace(fi.FullName, ".txt$", "") + ".zip"))
To delete your zip file after you decompress it, put the following line in your Decompress method as the very last line (outside your outer-most using statement):
File.Delete(fi);
You probably want to wrap that in a try-catch but this is the basic code to run. Here is an article on how to delete a file safely:
http://www.dotnetperls.com/file-delete